This is the 7th day of my participation in Gwen Challenge
Relearn JavaScript in a series of articles…
This is not a JavaScript specific feature; it also exists in object-oriented languages such as c++ and Java. The “this” of them makes sense, pointing to an instance object of the current class. What about in JavaScript? Let’s look at two examples:
function Person(name){ this.name = name } // 1. As a constructor call, let p = new Person(' programmer ') // Output: programmer // Can see that the instance can access the property bound to this, which points to p instance // Since the new operator can change this to point to p instance // see the previous article for details: Object console.log(p.name) // 2. Function Man(name){this.name = name} Man(' programman ') console.log(window.name) // programman, this refers to the window object, Man function has no objectCopy the code
As you can see from the example, as the function executes, a this value is generated that holds the value of the object on which the function was called. Therefore, it can be inferred that this always refers to the caller of the function.
Here are a few scenarios to which this points:
- When a function is called without an object to which it belongs, this points to a global object
Var val = 1 var obj = {val:2, method:function(){let foo = function(){console.log(this.val)} foo() So this refers to window}} obj.method() // 1Copy the code
- This points to the owning object
Var var = 1 var obj = {val:2, method:function(){console.log(this.val)}} obj.method() // 2, this refers to the function object objCopy the code
- This refers to the object rebound after the call/apply/bind function was called
Var var obj = {val:2} var method = function(){console.log(this.val)} method() Call (obj) // 2,call changes the body of the function call to obj method.apply(obj) // 2,apply changes the body to obj var newM = Method.bind (obj) // bind changes the body to obj newM() // 2Copy the code
Here’s another classic example:
function f(k){ this.m = k return this } var m = f(1) var n = f(2) console.log(m.m) // 2.m undefind console.log(n.m) // 2 window.n.m = window.m = 2Copy the code
The f() call has no owning object, so this points to the window.
When f(1), this.m = window.m = 1, return this, that is, return window, so window.m = window.
When f(2) is executed, this also refers to window, this.m = window.m = 2, and the return statement assigns window to n, where window.n = window.
So m.m = 2.m, undefined; N = (window.n). M = window.m = 2.
So far we have learned the general knowledge about the direction of this.
The new operator changes the point of this.
Relearn JS | deep understanding of the Object, will be knowledge