如今的前端门槛愈来愈高,再也不是只会写写页面那么简单。模块化、自动化、跨端开发等逐渐成为要求,可是这些都须要创建在咱们牢固的基础之上。无论框架和模式怎么变,把基础原理打牢才能快速适应市场的变化。下面介绍一些经常使用的源码实现:javascript
call
用于改变函数this
指向,并执行函数前端
通常状况,谁调用函数,函数的this
就指向谁。利用这一特色,将函数做为对象的属性,由对象进行调用,便可改变函数this
指向,这种被称为隐式绑定。apply
实现同理,只需改变入参形式。java
let obj = {
name: 'JoJo'
}
function foo(){
console.log(this.name)
}
obj.fn = foo
obj.fn() // log: JoJo
复制代码
实现数组
Function.prototype.mycall = function () {
if(typeof this !== 'function'){
throw 'caller must be a function'
}
let othis = arguments[0] || window
othis._fn = this
let arg = [...arguments].slice(1)
let res = othis._fn(...arg)
Reflect.deleteProperty(othis, '_fn') //删除_fn属性
return res
}
复制代码
使用markdown
let obj = {
name: 'JoJo'
}
function foo(){
console.log(this.name)
}
foo.mycall(obj) // JoJo
复制代码
bind
用于改变函数this
指向,并返回一个函数app
注意点:框架
Function.prototype.mybind = function (oThis) {
if(typeof this != 'function'){
throw 'caller must be a function'
}
let fThis = this
//Array.prototype.slice.call 将类数组转为数组
let arg = Array.prototype.slice.call(arguments,1)
let NOP = function(){}
let fBound = function(){
let arg_ = Array.prototype.slice.call(arguments)
// new 绑定等级高于显式绑定
// 做为构造函数调用时,保留指向不作修改
// 使用 instanceof 判断是否为构造函数调用
return fThis.apply(this instanceof fBound ? this : oThis, arg.concat(arg_))
}
// 维护原型
if(this.prototype){
NOP.prototype = this.prototype
fBound.prototype = new NOP()
}
return fBound
}
复制代码
使用模块化
let obj = {
msg: 'JoJo'
}
function foo(msg){
console.log(msg + '' + this.msg)
}
let f = foo.mybind(obj)
f('hello') // hello JoJo
复制代码
new
使用构造函数建立实例对象,为实例对象添加this
属性和方法函数
new
的过程:ui
function new_(){
let fn = Array.prototype.shift.call(arguments)
if(typeof fn != 'function'){
throw fn + ' is not a constructor'
}
let obj = {}
obj.__proto__ = fn.prototype
let res = fn.apply(obj, arguments)
return typeof res === 'object' ? res : obj
}
复制代码
在ES5中,咱们可使用 Object.create
来简化这个过程:
function new_(){
let fn = Array.prototype.shift.call(arguments)
if(typeof fn != 'function'){
throw fn + ' is not a constructor'
}
let obj = Object.create(fn.prototype)
let res = fn.apply(obj, arguments)
return typeof res === 'object' ? res : obj
}
复制代码
instanceof
判断左边的原型是否存在于右边的原型链中。
实现思路:逐层往上查找原型,若是最终的原型为null
时,证实不存在原型链中,不然存在。
function instanceof_(left, right){
left = left.__proto__
while(left !== right.prototype){
left = left.__proto__ // 查找原型,再次while判断
if(left === null){
return false
}
}
return true
}
复制代码
Object.create
建立一个新对象,使用现有的对象来提供新建立的对象的__proto__,第二个可选参数为属性描述对象
function objectCreate_(proto, propertiesObject = {}){
if(typeof proto !== 'object' && typeof proto !== 'function' && proto !== null){
throw('Object prototype may only be an Object or null:'+proto)
}
let res = {}
res.__proto__ = proto
Object.defineProperties(res, propertiesObject)
return res
}
复制代码
深拷贝为对象建立一个相同的副本,二者的引用地址不相同。当你但愿使用一个对象,但又不想修改原对象时,深拷贝是一个很好的选择。这里实现一个基础版本,只对对象和数组作深拷贝。
实现思路:遍历对象,引用类型使用递归继续拷贝,基本类型直接赋值
function deepClone(origin) {
let toStr = Object.prototype.toString
let isInvalid = toStr.call(origin) !== '[object Object]' && toStr.call(origin) !== '[object Array]'
if (isInvalid) {
return origin
}
let target = toStr.call(origin) === '[object Object]' ? {} : []
for (const key in origin) {
if (origin.hasOwnProperty(key)) {
const item = origin[key];
if (typeof item === 'object' && item !== null) {
target[key] = deepClone(item)
} else {
target[key] = item
}
}
}
return target
}
复制代码
发布订阅模式在实际开发中能够实现模块间的彻底解耦,模块只须要关注事件的注册和触发。
发布订阅模式实现EventBus:
class EventBus{
constructor(){
this.task = {}
}
on(name, cb){
if(!this.task[name]){
this.task[name] = []
}
typeof cb === 'function' && this.task[name].push(cb)
}
emit(name, ...arg){
let taskQueue = this.task[name]
if(taskQueue && taskQueue.length > 0){
taskQueue.forEach(cb=>{
cb(...arg)
})
}
}
off(name, cb){
let taskQueue = this.task[name]
if(taskQueue && taskQueue.length > 0){
if(typeof cb === 'function'){
let index = taskQueue.indexOf(cb)
index != -1 && taskQueue.splice(index, 1)
}
if(typeof cb === 'undefined'){
this.task[name].length = 0
}
}
}
once(name, cb){
let callback = (...arg) => {
this.off(name, callback)
cb(...arg)
}
typeof cb === 'function' && this.on(name, callback)
}
}
复制代码
使用
let bus = new EventBus()
bus.on('add', function(a,b){
console.log(a+b)
})
bus.emit('add', 10, 20) //30
复制代码