Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deeply understand this in JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

It is believed that many inexperienced people have no idea about how to deeply understand this in JavaScript. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Define

This is the internal object that is automatically generated when the function runs, that is, the object from which the function is called. (it's not necessarily a precise definition, but it's easy to understand.) in most cases, the value of this is determined by how the function is called, it cannot be set by assignment during execution, and it may have a different value each time it is executed.

Global execution environment (outside function)

In the global execution environment, the this always points to the global object (global object), whether in strict mode or non-strict mode.

Code 1

Console.log (this.document = = document); / / true / / in the browser, the window object is the global object (global object) console.log (this = window); / / true this.a = 37; console.log (window.a); / / 37

Function execution environment (inside function)

In a function execution environment, the value of this depends on how the function is called.

There are four main ways to call functions:

Function is called directly

Object method call

Constructor call

Call / apply / bind

Arrow function (ES6)

Function is called directly

When the following code is executed in non-strict mode, the value of this points to the global object; in strict mode, the value of this defaults to undefined.

Code 2

/ * non-strict mode * / function F1 () {return this;} console.log (F1 () = window); / / true / / in node; console.log (F1 () = global); / / true / * strict mode * / function f2 () {'use strict' return this;} console.log (F1 () = undefined); / / true

Call / apply / bind changes the direction of this

Call / apply

The usage of call is similar to that of apply, except that the later parameters are passed in different forms.

Code 3

Function add (c, d) {return this.a + this.b + c + d;} var o = {a: 1, b: 3}; / / the first parameter of call is the object, which is the pointing object of this. The following argument is add.call (o, 5, 7), a member of the function arguments object; / / 1 + 3 + 5 + 7 = 16 / / the first parameter of the call is the object, which is the pointing object of the this. The next parameter is the array, and the member of the array is the function arguments object member add.apply (o, [10,20]); / / 1 + 3 + 10 + 20 = 34

One thing to note when using call and apply is that when the value of the first parameter passed in is not an object, JavaScript attempts to convert it to an object using the ToObject operation.

Code 4

Function bar () {console.log (Object.prototype.toString.call (this));} bar.call (7); / / [object Number]

Bind method

ECMAScript 5 introduces Function.prototype.bind. Calling f.bind (someObject) creates a function with the same function body and scope as f, but in this new function, this will be permanently bound to the first parameter of bind, no matter how the function is called.

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Code 5

Function f () {return this.a;} var g = f.bind ({a: 'azerty'}); / / generate a binding function g console.log (g ()); / / azerty var o = {a: 10, f: F, g: G}; console.log (o.f (), o.g ()) / / 10, azerty / / Note that binding functions can no longer bind var h = g.bind ({a: 'foo'}); console.log (h ()); / / azerty, and will not become foo

Object method call

When a function is called as a method in an object, their this is the object that calls the function.

In the following example, when o.f () is called, the this within the function is bound to the o object.

Var prop = 36; var o = {prop: 37, bar: function () {return this.prop;}}; console.log (o.bar ()); / / 37

Constructor call

Code 6

Function Person (name, age) {this.name = name; this.age = age; this.introduce = function () {console.log ('My name is'+ this.name +', I\'m'+ this.age);};} var Joseph = new Person ('Joseph', 19); Joseph.introduce (); / / "My name is Joseph, item19"

From the above code, you can clearly see that this is bound to the newly created object.

Note: when the default value returned by the constructor is an object referenced by this, you can manually set it to return other objects, and return this if the returned value is not an object. This sentence seems difficult to understand. Let's take a look at the next example.

Code 7

Function Fn2 () {this.a = 9; / / dead code return {a: 10};} var o = new Fn2 (); console.log (o.a); / / 10

This example shows that when the constructor returns an object, the value of this becomes the object returned at this time. 'this.a = 9' becomes the zombie code.

Arrowhead function

In the arrow function (Arrow functions), the value of this is determined by the closed execution environment. In a global environment, then it is assigned as a global object.

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Var globalObject = this; var foo = (() = > this); console.log (foo () = globalObject); / / true

More importantly, unlike other cases, the value of the above this is always a global object no matter how the function is called. Call / bind cannot change its value either.

Code 8

/ / called as an object method var obj = {foo: foo}; console.log (obj.foo () = globalObject); / / true / / try to change the value of this with call console.log (foo.call (obj) = globalObject); / / true / / this does not change to obj / / try to change the value of this with bind foofoo = foo.bind (obj); console.log (foo () = = globalObject); / / true

Case

I have read all the knowledge points of this article. Let's look at a few cases and check our mastery.

Example 1

Var prop = 36; var o = {prop: 37, bar1: function () {function foo1 () {return this.prop;} return foo1;}, bar2: function () {var foo2 = (() = > this.prop); / / ES6 arrow function return foo2;}}; console.log ('result1:'+o.bar1 () ()); / / result1? Console.log ('result2:'+o.bar2 () ()); / / result2? Var fn2 = o.bar2; console.log ('result3:'+fn2 () ()); / / result3?

First, the answer is revealed: example 1 result1 = 36 result 2 = 37 result 3 = 36. My understanding is that in result1, the o.bar1 () execution causes the foo function return to be in the global environment, and then the execution becomes executed in the global, so you get the value of 36 in the global. Where's result2? Because this is in the arrow function. Its value will not change. So this still points to o. So why has result3 changed again? Because at this point, 'var fn2 = o.bar2' is equivalent to redefining a function, and the value of this is, of course, a global object.

/ / equivalent to var fn2 = function () {function foo1 () {return this.prop;} return foo1;} fn2 () ()

Example 2

Function sum (this.num b) {return aforb;}; var o = {num: 1, fn: function () {function handle () {return this.num = sum (this.num, this.num);} handle ();}}; console.log ('result:'+o.fn ()); / / result?

Also reveal the answer first: result = undefined, you can see that this points to window instead of o at this time on the console. This is a relatively easy to fall into the pit (generally believed to be the original language design errors, criticized by a lot of people). It seems that the function is called by the object method, but if we are careful, we can see. The execution of the handle function, in front of which there is no object. In this case, the this points to the global object. The solution is also simple.

/ / 1. Cancel the definition of the handle function and directly use this fn2 in the method of the object: function () {this.value = sum (this.value, this.value); / / 2}, / 2, use variables to save the this of the external function. Fn3: function () {var that = this; / / that = = o function handle () {that.value = add (that.value, that.value);} handle ();}

After reading the above, have you mastered how to understand this deeply in JavaScript? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report