js inside call () using

is to change the call context (context) runs a function exists, in other words, this is to change the function of the internal body points.
JavaScript is a major feature is that "when defining the context of" presence function and "run-time context" and "context can be changed," such a concept.

function fruits() {}
 
fruits.prototype = {
    color: "red",
    say: function() {
        console.log("My color is " + this.color);
    }
}
 
var apple = new fruits;
apple.say();    //My color is red

However, if we have an object banana = {color: "yellow"}, we do not want to say it redefine methods, we can say with a call or apply methods of apple:

banana = {
    color: "yellow"
}
apple.say.call(banana);     //My color is yellow
apple.say.apply(banana);    //My color is yellow

What's inside the method say "this" points to banana objects, so print out the color is yellow;

So, you can see call to change this dynamic that occurs when an object is not a method (this method chestnuts in banana does not say), but there are other (apple there say the method of the chestnut), we can make use of call or apply the method to manipulate other objects. 

 

 

Guess you like

Origin www.cnblogs.com/luzhanshi/p/11982477.html