1.闭包
a.即使创建它的上下文已经销毁,它依然存在;
b.在代码中引用了自由变量(自由变量是指在函数中使用的,但既不是函数参数也不是函数的局部变量的变量)。
2.call和apply的模拟实现
Function.prototype.call = function (context) {
context = context || window
context.fn = this
var args = []
for (let i = 1,len =arguments.length; i < len; i++) {
args.push(`arguments[+${i}+]`)
}
let result = eval(`context.fn(${args})`)
delete context.fn
return result
}
3.bind的模拟实现
a.bind会创建一个新函数,当函数被调用时,bind的第一个参数指向this。
b.bind返回的函数作为构造函数,bind指定的this值会失效,但传入的参数有效。
Function.prototype.bind = function (context) {
if ( typeof this !== 'function') {
throw new Error('Function.prototype.bind - what is trying to be bound is not callable')
}
let selt = this
let args = Array.prototype.slice.call(arguments, 1)
let fNOP = function () {}
let fBound = function () {
let bindArg = Array.prototype.slice.call(arguments, 1)
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArg))
}
fNOP.prototype = this.prototype
fBound,.prototype = new fNOP()
return fBound
}
4.new的模拟实现
function objectFactory () {
var obj = new Object()
Constructor = [].shift.call(arguments)
obj.__proto__ = Constructor.prototype
var ret = Constructor .apply(obj, arguments)
return typeof ret === 'object' ? ret : obj
}
参考:https://github.com/mqyqingfeng/Blog/issues/11