当前位置:网站首页>The difference between bind, call and apply, and the encapsulation of bind()

The difference between bind, call and apply, and the encapsulation of bind()

2022-06-12 12:05:00 Mustang (Mustang)

1.bind、call、apply Differences among the three :
  1)bind The return value of is a function body , Will not be called immediately
  2)call、apply Will immediately call , The first parameter is used to change this The direction of , The difference between the two is that the former passes parameters one by one , The latter is passed as an array
  3)bind、call、apply These three methods are all functions (Function) Methods
2.bind Encapsulation :
bind Characteristics :(1) Returns the body of a function (2) change this The direction of (3) Pass parameters
Original bind Method can be implemented :(1)this Changes (2) You can inherit your own prototype methods (3)new After oneself this Pointing to the constructor is itself ( Constructor's this Point to instance object )

Function.prototype.bindTo = function(){
    // The first parameter passed , That is, the this Point to ( Use arguments Formal parameter copy to receive all parameters )
    var that = arguments[0];
    // Get the remaining parameters 
    //slice The method is to split the array , Parameter is 1 Is for splitting from the second item of the array , Until the last item of the array 
    var arr = Array.prototype.slice.call(arguments).slice(1);
    var _this = this;// Current this Point to bindTo This function 
    var fn = function(){
        // Point current to bindTo Functional this To change ,that Indicates what needs to be changed this Point to , adopt apply Methods to change 
        //arr For other parameters that need to be passed 
        //this instanceof fn What is judged is whether it is currently new too , If new After that , Now this Should point to the constructor itself ( Constructor's this Point to the instantiated object ), and this Just point to the current bindTo function ; without new too , Now this It should point to the passed parameter ( Implement change this The direction of )
        var newThis = this instanceof fn?this:that;
        _this.apply(newThis ,arr);
    }
    // Implementation inheritance 
    fn.prototype = {
        constructor:fn,
        __proto__:this.prototype
    }
    return fn;
}

perform :

function Fn(a,b,c){
    console.log(this,a,b,c);
}
Fn.prototype = {
    show(){}
}
var fn1 = Fn.bindTo(document);// The original this It's pointing window Of , In the use of the bindTo Method can be used to this Point to document
var p = new fn1();//new After that, I will this Point to Fn(), The constructor itself ( Constructor's this Point to instance object )
console.log(p);// Print p You can inherit show() Prototype method 
原网站

版权声明
本文为[Mustang (Mustang)]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121158414668.html