In JavaScript, if the function belongs to an object, the behavior of accessing the function through the object is called "method call". Unlike ordinary function calls, when making a method call, this reference in the function will change - this will refer to the object used to call the function (this object will become the invocation context of the method call):
The code copy is as follows:
var x = 99;
var sample = {
x:1,
act:function(a){
this.x = a*a;//assign value to sample's x, not global object's x.
}
}
sample.act(6);
console.log(sample.x);//36
console.log(x);//99
Like accessing properties in objects, in addition to using dot operators, JavaScript can also use bracket operators to make method calls:
The code copy is as follows:
//other ways to invoke method
sample["act"](7);
console.log(sample.x);//49
For functions in JavaScript, an interesting behavior is to embed functions (closures) in functions. When making a method call, if there is an embedded function in the method function, the code in this embedded function can access the external variable value:
The code copy is as follows:
//nested function can access variable outside of it.
var y = 88;
var sample2 = {
y:1,
act2:function(a){
this.y = inner();
function inner(){
return a*a;
}
}
}
sample2.act2(8);
console.log(sample2.y);//64
console.log(y);//88
However, contrary to intuition, code embedded in the function cannot inherit this from the outside; that is, in the embedded function, this refers not to the object that calls the method, but to the global object:
The code copy is as follows:
//nested function does not inherit "this". The "this" in nested function is global object
var sample3 = {
act3:function(){
inner();
function inner(){
console.log(this);//window object
}
}
}
sample3.act3();
If you really need to access the object that calls the method in the embedded function, you can save this value into a variable in the external function:
The code copy is as follows:
//pass "this" to nested function
var sample4 = {
act4:function(){
var self = this;
inner();
function inner(){
console.log(self);//Object {act4=function()}
}
}
}
sample4.act4();