Call method
Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Approximate wording: Call (object,arg1,arg2,...);
Definition: Invokes one method of an object, replacing the current object with another object.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
The definition of the document is slightly tall, read or foggy, or through a few simple code to explain:
First, let's take a look at this piece of code
function Animal () { console.log (this);}
Animal (); //Output Window
This is the equivalent of Animal.call (undefined), this is the inside of the undefined, supposedly should be printed out undefined, but the browser has a rule:
In non-strict mode when our first argument is passed to null or undefined, this in the body of the function points to the default host object, which in the browser is the window
As shown in the following example, FN is not a method of obj, but with call we can bind the this inside FN to obj and then use THIS.A to access the A property of obj.
var a = ten;
function fn () {
Console.log (this . a);
Console.log (this );
}
var obj = {
a:20
}
fn (); //10,window
Fn.call (obj); //20,obj
var Animal = { ' words ', function(str) { console.log (str +this . Word); } } Animal.say (' speak '); //speak Words
var cat = {
Word: ' Miao '
}
Animal.say.call (cat, ' speak '); //speak Miao
In the example above, we define a animal object that has the word property and the Say method, which can get its word value by Animal.say (). Then define a cat, which is given the word attribute only, Animal.say () is theoretically pointing to Animal, but the call method changes the execution context and Animal.say this point to cat.
Implementing inheritance
function Animal (words) { this. words=words, this. say=function() { Console.log (this. words); } } function Cat (words) { Animal.call (this, words); } var New Cat (' Miao '); Cat.say (); Miao
The understanding and call () of context this in JavaScript is used