The previous two articles describe two important properties in the JavaScript execution context: Vo/ao and scope chain. This article looks at the this in the execution context.
First take a look at the following two summary of this:
- This is an important property of the execution context (execution context) and is a special object related to the execution context. Therefore, it can be called a context object (that is, an object that indicates the context in which the execution context was triggered).
- This is not a property of a Variable object (Variable objects) , so unlike variables, this never participates in the identifier parsing process. That is, when this is accessed in code, its value is obtained directly from the execution context and does not require any scope chain lookups. The value of this is determined only once when the context is entered.
The most confusing thing about this is that the same function, when called in a different context, may have a different value. That is, the value of this is provided by the caller of the function call expression (that is, how the function is called).
The following is a look at the value of this in different scenarios.
Global context
In the global context, this is always global object, which is the window object in the browser.
Console.log (this= = = window); THIS.name = "would"; This.age =; function() {Console.log (this.age + "years old");}; Window.getinfo (); // true// would is-years old
function context
In a function, this is a lot more, the value of this is directly affected by the way the function is called.
Invoke function as function
When a function is called in a normal way, the value of this is set to global object (the Window object in the browser).
However, this will be set to "undefined" when the following code is executed using "strict mode".
function Gfunc () {This ;} Console.log (Gfunc ()); Console.log (this= = = Window.gfunc ()); window// true
Invoke function as Method
When a function executes as an object method, the value of this is the object to which the method belongs.
In the following example, an Obj object is created and the value of the Name property is set to "obj". Therefore, when invoking the Func method of the object, this in the method represents the object of obj.
var obj = { name: ' obj ', function () { Console.log (this. Name);}};o Bj.func (); // [object object]:obj
To verify that the this in the method represents the object that the method belongs to, look at the following example.
In Object obj, an inline object nestedobj is created, and this in the method represents nestedobj when the method of the inline object is called.
var obj = { name: "obj", nestedobj: { name: "Nestedobj", function () {Console.log ( this. name);} }}obj.nestedobj.func (); // [object object]:nestedobj
For the methods in the example above, it is often called a binding method, meaning that these methods are associated with a particular object.
However, when we do the following, temp will be a function within the global function and not bound to the Obj object. Therefore, this in temp represents the Window object.
var name = "would"; var obj = { name: "obj", function () {Console.log (this. name);}}; temp = obj.func;temp (); [Object Window]:will
Invoke function as Constructor
In JavaScript, a function can be used as a constructor to create objects directly, in which case this represents the newly created object.
Function staff (name, age) { this.name = name; this.age =function() {Console.log (this.age + "years old");};} new Staff ("would",will.getinfo ); years old
Invoke context-less function
For some functions that have no context, which means that these functions are not bound to a particular object, the context-independent functions will be bound to the global object by default.
In this example, the function f and the anonymous function expression are not associated to any object during the call, so their this represents the global object.
var context = "Global";var obj ={context: ' object ', Method:function() {Console.log (This + ":" +This. context);function F () {var context = "function" this +": "+ this.context);}; f (); (functionvar Context = "function" this +": "+this.context); })(); }};obj.method (); // [Object Object]:object // [Object Window]:global // [object Window]:global Call/apply/bind Change this
This itself is immutable, but JavaScript provides call/apply/bind three functions to set the value of this when the function is called.
The prototypes of these three functions are as follows:
- Fun.apply (Obj1 [, Argsarray])
- Sets Obj1 as the value of this inside fun () and calls fun () passing elements of Argsarray as its arguments.
- Fun.call (obj1 [, Arg1 [, Arg2 [, Arg3 [, ...]]
- Sets Obj1 as the value of this inside fun () and calls fun () passing arg1, arg2, Arg3, ... as its arguments.
- Fun.bind (obj1 [, Arg1 [, Arg2 [, Arg3 [, ...]]
- Returns the reference to the function fun with this inside fun () bound to obj1 and parameters of fun bound to the Paramete RS specified arg1, arg2, Arg3, ....
Let's look at a simple example:
functionAdd (NumA, NumB) {Console.log (This.original + NumA + NumB);} Add (1, 2};add.apply (obj, [1, 2); var F1 = Add.bind (obj); F1 (2, 3 ); var F2 = Add.bind (obj, 2); // Nan// 13// 13// 15//
When the Add function is called directly, this will represent window, and when "this.original" is executed, it will get "undefined" because the window object does not have a "original" property.
By Call/apply/bind, the effect is to bind the Add function to the Obj object, and when add is called, this represents the object of obj.
DOM event Handler
When a function is treated as an event handler, this is set to the element of the page that triggers the events.
var BODY = document.getElementsByTagName ("body") [0function() { Console.log (this);}); // <body>...</body>
In-line event Handler
When the code executes through In-line handler, this also points to the page element that owns the handler.
Look at the following code:
document.write (' <button onclick= ' Console.log (This) ">show this</button>"); <button onclick= "Console.log (This)" >show this</button>document.write (' <button onclick= "( function () {console.log (this);}) () ">show this</button>"); // window
In the first line of code, as described above In-line handler, this will point to the Element "button". However, for anonymous functions in the second line of code, this is a context-independent (context-less) function, so this is set to window by default.
We've already covered the BIND function earlier, so we can change the behavior of the second line of code in the example above with the following modifications:
document.write (' <button onclick= ' (function () {console.log (this);}). Bind (This)) () ">show this</button>"); // <button onclick= "((function () {console.log (this);}). Bind (This)) () ">show this</button>
Save this
In JavaScript code, multiple this may appear in the same context, in order to use the outer this, the this is staged.
Look at the following example, according to the previous introduction, in the BODY element of the click handler, this is definitely pointing to the body of this element, so in order to use the "greeting" method, is to point to the bar object This is staged, here is a self variable.
With self, we can use the "greeting" method of the Bar object in the click handler.
When reading some JavaScript library code, if you encounter a similar self,me,that, they may be the temporary storage of this.
var bar = {name: "bar" Body:document.getElementsByTagName ("Bo Dy ") [0function () {Console.log ("Hi there, I ' m" + this + ":" + this.name); }, Anothermethod: function () {var self = thisthis.body.addeventlistener ("click", function () {self.greeting ();}); }}; Bar.anothermethod (); // Hi there, I ' m [Object Object]:bar
Similarly, for the example above, you can also use bind to set this to the same effect.
var bar ={Name: "Bar"function () {Console.log ("Hi there, I ' m" + this + ":" + this.name);}, Anothermethod: function () {this.body.addeventlistener (" click "," Span style= "color: #0000ff;" >function () {thisthis// Hi there, I ' m [Object Object]:bar Summarize
This article describes the This property in the execution context, and the value of this directly affects the running result of the code.
In a function call, this is provided by the caller (caller) of the activation context code, that is, the parent context of the calling function, that is, this depends on how the function is called, pointing to the object that the function is bound to when it was called.
Through the above introduction, I believe that this has a certain understanding.
The This in JavaScript