We say that the calling mode of a function is called as a function, and it is to distinguish it from the other three calling modes.
There are three other calls to the function: method calling mode, constructor calling mode, and apply/call calling mode.
Method calling mode:
var obj={ fun1: function(){ //Method content this; //Refers to window }}obj.fun1() //Method callConstructor call:
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); };}var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");apply/call call mode:
function cat(){}cat.prototype = { food: "fish", say: function(){ alert("I love " + this.food); }};var blackCat = new cat; blackCat.say();If there is no explicit return statement here, the new object will be returned implicitly and becomes the value of this constructor. In other words, it can be equivalent to: var blackCat = new cat();
But if we have an object
var whiteDog = { food: "bone"};We don't want to redefine the say method for it, then we can use the blackCat's say method by calling or applying:
blackCat.say.call(whiteDog);
Therefore, it can be seen that call and apply appear to dynamically change this. When an object does not have a certain method, but others are, we can use call or apply to operate with other object methods.
For more use, the dom node selected through document.getElementsByTagName is an array similar to array (arguments, etc.). It cannot apply push, pop and other methods under Array. We can use:
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
In this way, domNodes can apply all the methods under Array.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.