In JavaScript, the function's this keyword behaves a lot differently than other languages. There is also a slight difference between the strict and non-strict modes of JavaScript.
In most cases, the way the function is called determines the value of this. This cannot be assigned during execution, and the value of this may be different at each time the function is invoked. ES5 introduced the Bind method to set the this value of the function, regardless of how the function was called.
Global context
In the global run context (outside any function body), this refers to the global object, whether in strict mode or not.
1 console.log (this// true23// in the browser, the global object is Window object:4 console.log (this// true56this . A = PNs; 7 // Panax Notoginseng
function context
Inside the function, the value of this depends on how the function is called.
Call directly
1 function F1 () {2 return This ; 3 }45// true
In the above example, the value of this is not set by the function call. Because the code is not executed in strict mode, the value of this is always an object and defaults to a global object.
function F2 () { /// Here is strict mode returnthis// True
In strict mode, this is set when entering the running environment. If not defined, the value of this will maintain the undefined state. It can also be set to any value, such as null or 42 or " I am not this
".
Note : In the second example, this should be undefined. Because F2 is not called as a method (see below). This feature has not been implemented in all browsers that first started to support strict mode. So some browsers return the wrong result: the Window object.
This in the object method
When a function is called as a method in an object, their this is the object that called the function.
In the following example, when o.f()
called, the This within the function is bound to the O object.
1 var o = {2 prop:37,3 function() {4 returnthis. Prop; 5 }6}; 7 8 // logs Notoginseng
Note that where or how to define the calling function does not affect the behavior of this at all. In the previous example, we defined an anonymous function for its member F when we defined O. However, we can also define the function first and then attach it to the o.f
. The behavior of this is also consistent:
1 var o = {prop:37}; 2 3 function Independent () {4 return This . Prop; 5 }67 o.f = Independent; 8 9 // logs Notoginseng
This indicates that the value of this is only related to the invocation of function f as a member of O.
Similarly, this binding is only affected by the closest member reference. In the following example, we call a method g as a o.b
function of an object. During this execution, the this in the function points to o.b
. In fact, this does not matter much to the members of the object itself, and the closest reference is the most important.
1 o.b = {2 g:independent,3 prop:424}; 5 // logs
In the prototype chain
This
The same concepts are also consistent in defining the methods in the prototype chain. If the method exists on the prototype chain of an object, this refers to the object that called the method, acting as if the method existed on the object.
1 varo = {2F:function(){ 3 return This. A + This. b;4 }5 };6 varp =object.create (o);7P.A = 1;8P.B = 4;9 TenConsole.log (P.F ());//5
In this example, the object P does not belong to its own F attribute, its F attribute inherits from its prototype. However, this is not related to the discovery process of finding the F attribute in O, which begins with the P.F reference, so the this in the function points to p. That is, because F is called as a method of p, it points to p. This is an interesting feature of JavaScript's prototype inheritance.
Getter and setter in the This
Again, the same concept applies when the function is called as a getter or a setter. As getter or setter functions bind this to the object from which the property is set or obtained.
1 functionmodulus () {2 returnMATH.SQRT ( This. Re * This. Re + This. im * This. im);3 }4 5 varo = {6Re:1,7Im:-1,8 Get Phase () {9 returnMath.atan2 ( This. IM, This. Re);Ten } One }; A -Object.defineproperty (o, ' modulus ', { -Get:modulus, Enumerable:true, Configurable:true}); the -Console.log (O.phase, O.modulus);//logs-0.78 1.4142
This in the constructor
When a function is used as a constructor (using the New keyword), its this is bound to the new object that is about to be created.
Note: When the constructor returns the default value that is a this reference object, you can manually set the returned object to return if the return value is not an object, which returns this.
1 functionC () {2 This. A = 37;3 }4 5 varo =NewC ();6Console.log (O.A);//logs Notoginseng7 8 9 functionC2 () {Ten This. A = 37; One return{a:38}; A } - -o =NewC2 (); theConsole.log (O.A);//logs
In the last example (C2), because the return object was manually set during the call to the constructor, the default object that was bound to this is canceled (essentially this makes the statement " this.a = 37;
" zombie "code, which is actually not really a" zombie ", This statement executes but has no effect on the outside, so it can be completely ignored.
call
And
apply
When the This keyword is used in the function body of a function, its value can be bound to a specified object when all functions are invoked from the call () method and the Apply () method that inherit from the prototype of the function object.
1 functionAdd (c, D) {2 return This. A + This. B + C +D;3 }4 5 varo = {a:1, b:3};6 7 //The first parameter is the object to use as ' this ', subsequent parameters is passed as8 //arguments in the function call9Add.call (O, 5, 7);//1 + 3 + 5 + 7 =Ten One //The first parameter is the object to use as ' this ', the second are an array whose A //Members is used as the arguments in the function call -Add.apply (o, [10, 20]);//1 + 3 + + + =
Using call
and apply 函数的时候要注意,
if the this value passed is not an object, JavaScript will attempt to convert it to an object using an internal toobject operation. Therefore, if the value passed is a raw value such as 7
or ‘foo‘
, then it is converted to an object using the relevant constructor, so the original value is converted to an object, and the string is converted to an 7
new Number(7)
‘foo‘使用 new String(‘foo‘)
object, for example:
1 function Bar () {2 console.log (Object.prototype.toString.call (this)); 3 }45// [object number]
bind
Method
ECMAScript 5 was introduced Function.prototype.bind
. Callf.bind(someObject)会创建一个与f具有相同函数体和作用域的函数,但是在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
function f () { returnthis. A;} var g = F.bind ({A: "Azerty"// azertyvar o = {a:37// Panax Notoginseng, Azerty
This in the DOM event handler function
When a function is used as an event handler, its this point points to the element that triggered the event (some browsers do not adhere to this convention when adding listeners dynamically, unless the phrase "AddEventListener" is not sure if the translation is correct).
1 //when called, turns the associated element into blue2 functionbluify (e) {3Console.log ( This= = = E.currenttarget);//always True4 5 //when Currenttarget and target are the same object is true6Console.log ( This===e.target); 7 This. Style.backgroundcolor = ' #A5D9F3 ';8 }9 Ten //gets a list of all the elements in the document One varelements = document.getElementsByTagName (' * ')); A - //The bluify is used as the element's tap listener function, and when the element is clicked, it becomes Blue . - for(vari=0; I<elements.length; i++){ theElements[i].addeventlistener (' Click ', Bluify,false); -}
This in an inline event handler function
When the code is called by an inline handler, it points to the DOM element where the listener resides:
<button onclick= "alert (This.tagName.toLowerCase ()); > this </button>
The alert above will show the button. Note that only the this in the outer code is set:
<button onclick= "Alert ((function () {return This})" ()); > this </button>
In this case, the intrinsic function is not set this
, so it points to the global/window
object (that is, the function called in non-strict mode does not set the default object to which this is pointed).
The This keyword in javascript