this
- In the body of a function, a simple call to a function, either explicitly or implicitly, is bound to undeined in strict mode and to the global object Window/Global in non-strict mode.
- When a constructor is called using the new method, the this inside the constructor is bound to the newly created object
- When a function is explicitly called using the call/apply/bind method, the this inside the function is bound to the object with the specified argument
- When a function is called from a context object, the this of the function body is bound to that object
- In arrow functions, the reference to this is determined by the outer (function or global) scope
This in the global environment
function f1() {
console.log(this)}function f2() {
'use strict'
console.log(this)
}
f1() //Window {Window: Window, self: Window, document: document, name: "", location: location,... }
f2() //undefined
Copy the code
const o1 = {
text: 'ol'.fn: function() {
return this.text
}
}
const o2 = {
text: 'o2'.fn: o1.fn
}
console.log(o2.fn())//o2
Copy the code
const foo = {
bar: 10.fn: function() {
console.log(this)
console.log(this.bar)
}
}
var fn1 = foo.fn
fn1()
//Window {Window: Window, self: Window, document: document, name: "", location: location,... }
//undefined
Copy the code
- Here this still refers to the window, and while the fn function is used as the object’s method in foo, after assignment, fn1 still runs in the window’s global environment.
Constructor and this
function Foo() {
this.bar = "Lucas"
}
const instance = new Foo()
console.log(instance.bar)//Lucas
Copy the code
- The new operation symbol invokes the specific operation of the constructor
- A new object is created
- Point the constructor’s this to the object
- Add attributes and methods to this object
- The new object is eventually returned
var obj = {}
obj.__proto__ = Foo.prototype
Foo.call(obj)
Copy the code
function Foo() {
this.user = "Lucas"
const o = {}
return o
}
const instance = new Foo()
console.log(instance.user) //undefined
Copy the code
- If the constructor returns a value and returns an object, then this refers to the returned object, and if the return is not an object, this still refers to the instance
This in the arrow function
- This appears in the anonymous function of setTimeout, so this refers to the window object
const foo = {
fn: function() {
setTimeout(function() {
console.log(this)}}}console.log(foo.fn())
//undefined
//Window {Window: Window, self: Window, document: document, name: "", location: location,... }
Copy the code
const foo = {
fn: function() {
console.log(2)
setTimeout(() = > {
console.log(3)
console.log(this)}}}console.log(1)
console.log(foo.fn())
/ / 1
/ / 2
// undefined
/ / 3
// {fn:f}
Copy the code
- The binding of the arrow function cannot be modified
function foo() {
return a= > {
console.log(this.a)
};
}
const obj1 = {
a: 2
}
const obj2 = {
a: 3
}
var bar = foo.call(obj1)
console.log(bar.call(obj2))/ / 2
Copy the code