1.

Name Two Ways Two Change The Context Of A Javascript Method ?

Answer»

USE the call or apply METHODS

The call and apply methods can be used to specify the context of another method.

VAR objectA = {
NAME : "I am objectA",
sayName : function(){
alert("I am: " + this.name);
}
},
objectB = {
name : "objectB",
sayName : function(){
alert("I am: " + this.name);
}
};
objectA.sayName.call(objectB); //ALERTS: "I am ObjectB"
objectB.sayName.apply(objectA); //alerts: "I am ObjectA"

Use the call or apply methods, 

The call and apply methods can be used to specify the context of another method.

var objectA = {
name : "I am objectA",
sayName : function(){
alert("I am: " + this.name);
}
},
objectB = {
name : "objectB",
sayName : function(){
alert("I am: " + this.name);
}
};
objectA.sayName.call(objectB); //alerts: "I am ObjectB"
objectB.sayName.apply(objectA); //alerts: "I am ObjectA"



Discussion

No Comment Found