The magic call of method in JavaScript

  • 2020-05-16 06:17:51
  • OfStack

Take a look at the official explanation for call(), "calling one method of one object to replace the current object with another." This explanation may make you even more confused. See the examples:


var x = " I'm a global variable ";    // Defining global variables x
function a(){         // Define the function class structure a  
    this.x = " I'm in a function class structure a That was declared in ";   
}
// Defines a normal function that pops up the variables contained in the current pointer x The value of the
function f(){      
    alert (this.x);
}
// The return value is "I am in a function class structure a "Declared in" oh."
f.call(new a());

As I understand it, f.call (new a()) copies the function (which is also an object) f under the called object "new a()" to parse, which is actually the same as the parsing result of the following code:

function a(){
  this.x = " I'm in a function class structure a That was declared in ";
  alert(this.x);   
}
a();

It's just that the scope of the variable X is different. Looks like a little bit of inheritance, doesn't it? In the above example,f is completely inherited by the power object of the constructor a. If this is not enough to show that a.call (b) is an inheritance mode, then let's look at a more inheritance flavor.

function f(){   
    this.a ="a";   
    this.b = function(){   
        alert("b");
    }
}
function e(){   
    f.call(this);    
}
var c = new e();
alert(c.a);  // The pop-up a
c.b();    // The pop-up b

In this example, anyone who knows how to use a browser can see that e fully inherits the properties and methods of f. Otherwise, it cannot be explained, because e does not define the properties a and b, so it is reasonable to infer that e's instance object c does not have these two properties.


Related articles: