call apply bind
都是改变this 的指向 区别 就是传入的参数格式不同
- call fn.call(this, age, name )
- apply fn.apply(this, [ age, name ] )
实现call
Function.prototype.myCall = function (context) {
var _this = context || window
_this.fn = this
var args = [...arguments].slice(1)
var reulst = _this.fn(...args)
delete _this.fn
return reulst
}
实现 apply
Function.prototype.myApply = function (context) {
var _ = context || window
_.fn = this
var reulst;
if (arguments[1]) {
reulst = _.fn(...arguments[1])
} else {
reulst = _.fn()
}
delete _.fn
return reulst
}
实现 bind
Function.prototype.myBind = function (context) {
if(typeof this !== 'function') {
return new TypeError('Error')
}
var _this = this
var args = [...arguments].slice(1)
return function Fn() {
if( this instanceof Fn ) {
return _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
let obj = {
name: 1,
age: 2,
sex: '男'
}
function fn(name,age) {
console.log(name,age);
this.name = name
this.age = age
}
fn.myBind(obj,'zhang', 12)()
console.log(obj);