This article describes various methods of modifying the this pointer in JavaScript. If you don’t know about modifying the this pointer in JavaScript or are interested in modifying the this pointer in JavaScript, then we will Let's get up and read this article. Okay, let's cut the nonsense and get to the point
This in JavaScript is a topic worthy of in-depth discussion. The following summarizes 3 common methods of changing the point of this. First, clarify the concept of function: the function itself is a special type. You must always understand that a function can also be considered a variable.
In layman's terms, if this function is a method (key) of an object, then this in the function points to this object.
var a = function(obj) { alert(this == obj); } var obj = {}; obj.fun = a; obj.fun(obj); //true
This function is equivalent to a variable. When it is bound to an object, then this point will be changed from the default window objectChange to obj object.
var obj = new a();
A new object is created through this statement, and this in the function points to obj.
1.apply method
param1 : The pointer of this in the show function
param2: a collection []
Example: called function name.apply(param1, param2);
Review the first method
var a = function(o) { alert(this == o); } var obj = {}; obj.fun = a; obj.fun(obj); //true
Simple, just apply one sentence
a.apply(obj,[obj]);
2.call method
param1: show The point of this in the function
param2: The second parameter starts with the actual parameters of the show function
Example: Called function name.call(param1,param2,param3);
a.call(obj,obj);
Simple example:
Add styles to multiple elements through each function
function each(tagName, callback) { var lists = document.getElementsByTagName(tagName); for (var i = 0; i < lists.length; i++) { callback.apply(lists[i]); } } each("a", function () { this.style.background = "#ccc"; }
The above is all the content of this article. If you don’t know much about it yet, If you can implement both sides by yourself, it will be easy to master!
Related recommendations:
Four types of this value modes in JS
Four binding forms of this in javascript functions
The above is the detailed content of Various ways to modify what this points to in JavaScript. For more information, please follow other related articles on the PHP Chinese website!