This article mainly introduces method calls in JavaScript. in JavaScript, if a function belongs to an object, the behavior of accessing the function through an object is called "method call ", for more information, see JavaScript. if a function belongs to an object, the behavior of accessing the function through an object is called "method call ". Unlike common function calls, this in function indicates that the change will occur-this indicates the object used to call the function (the object will be the invocation context of the method call ):
The code is as follows:
Var x = 99;
Var sample = {
X: 1,
Act: function (){
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 the property in an object, in addition to the dot operator, JavaScript can also call methods by using the brackets operator:
The code is as follows:
// Other ways to invoke method
Sample ["act"] (7 );
Console. log (sample. x); // 49
An interesting behavior for functions in JavaScript is that functions (closures) can be embedded in functions ). When calling a method, if the method function contains an embedded function, the code in the embedded function can access the external variable value:
The code is as follows:
// Nested function can access variable outside of it.
Var y = 88;
Var sample2 = {
Y: 1,
Act2: function (){
This. y = inner ();
Function inner (){
Return a *;
}
}
}
Sample2.act2 (8 );
Console. log (sample2.y); // 64
Console. log (y); // 88
However, contrary to intuition, the code embedded in a function cannot inherit this from the outside. that is to say, in an embedded function, this is not an object that calls a method, but a global object:
The code 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 do need to access the object that calls the method in the embedded function, you can save this value to a variable in the external function:
The code 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 ();