apply,call,bind method

1. Apply and call exist to change the context of function runtime, which is often referred to as this

		function fruits() {}
		 
		fruits.prototype = {
		    color: "red",
		    say: function() {
		        console.log("My color is " + this.color);
		    }
		}
		 
		var object = new fruits;
		object.say();    //My color is red
		//When another object needs to use the say method, it can be undefined
		var otherObject = {
		 	color : " yellow""
		};
		//call/apply can be used at this time
		object.say.call(otherObject); //My color is yellow
		object.say.apply(otherObject); //My color is yellow

2. The difference between call and apply: they have the same function, but the way to receive parameters is different. Call needs to pass parameters in order, while apply puts parameters in array

	var array1 = [12 , "foo" , {name:"Joe"} , -2458]; 
	var array2 = ["Doe" , 555 , 100]; 
	Array.prototype.push.apply(array1, array2); 
	// array1 values are [12, "foo", {Name: "Joe"}, - 2458, "DOE", 555, 100] 

Commonly used to determine whether an object is an array:

	Object.prototype.toString.call(obj) //If yes, '[object Array]' will be output

And pseudo array to array

	Array.prototype.slice.call(document.getElmentsByTagName("*"))

3. bind method

	this.num = 9; 
	var mymodule = {
	  num: 81,
	  getNum: function() { 
	    console.log(this.num);
	  }
	};
	
	mymodule.getNum(); // 81
	
	var getNum = mymodule.getNum;
	getNum(); // 9, because in this case, "this" points to a global object
	
	var boundGetNum = getNum.bind(mymodule);
	boundGetNum(); // 81

The above method actually changes the direction of this. In our work, we often use "this" or "that" to save this. We might as well use the bind method to solve this problem more elegantly
For example:

	var foo = {
    bar : 1,
    eventBind: function(){
        $('.someClass').on('click',function(event) {
            /* Act on the event */
            console.log(this.bar);      //1
        }.bind(this));
    }
}

The above example uses bind to change the direction of this. Before it is changed, it points to the back click element. There is no bar attribute, so you need to use "this" or "that" to save this

All three can change the direction of this

Tags: Attribute

Posted on Sat, 30 Nov 2019 03:45:29 -0800 by KingPhilip