如何封装一个函数达到call(),bind(),apply()同样的效果呢?
var obj = {
name: '张三',
age: 24,
fn: function (a, b) {
console.log(this.name, a, b);
}
}
var sc = {
name: '李四',
}
封装call
Function.prototype.mycall = function (newobj, argus) {
var newname = Symbol(this.name);
newobj[newname] = this;
var val = newobj[newname](...argus);
delete newobj[newname];
return val;
}
obj.fn.mybind(sc,'hh','kk');
封装apply
Function.prototype.myapply = function (newobj, arg) {
var newname = Symbol(this.name);
newobj[newname] = this;
var val = newobj[newname](...arg);
delete newobj[newname];
return val;
}
obj.fn.mybind(sc,【'hh','kk'】);
封装bind()
Function.prototype.mybind=function(newobj,...arg){
var that=this;
return function(){
that.myapplay(newobj,arg.concat(...arguments));
}
}
var ss=obj.fn.mybind(sc,'dd');
网友评论