美文网首页
封装call bind()apply

封装call bind()apply

作者: 拾柒_aab0 | 来源:发表于2019-11-17 20:35 被阅读0次

如何封装一个函数达到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');

相关文章

网友评论

      本文标题:封装call bind()apply

      本文链接:https://www.haomeiwen.com/subject/ntvpictx.html