Study notes-this pointer in JS points to the problem


In javascript, the this pointer points to the problem is an important knowledge point. In different situations, the direction this pointer points to will be different.

1. The function name directly adds parentheses to call the function, then this points to the global object window

 

var a = 100;
function getA() { 
    var a = 10;
    console.log(this.a); 
};
getA();

2. When the function bound to the label event is called, this points to the label that triggered the event

// HTML:<button class="button">确定</button>

// js
var a = 100;
document.querySelector('.button').onclick = function() {
	var a = 200;
	console.log(this); // <button class="button">确定</button>
};

 

3. Through the object point to call a function of the object, this points to the calling object

var a = 100;
var obj = {
    a: 20,
    b: function() { 
        var a = 30;
		console.log(this.a);
	}
};
obj.b();    // 20

 

4. Call an arrow function of the object through the object point , this points to the calling object

var a = 100;
var obj = {
    a: 20,
    b: () => { 
        var a = 30;
		console.log(this.a);
	}
};
obj.b();    // 100

Note: The arrow function has already determined the this pointer when it is declared, and cannot be changed in the future.

5. The new function, this pointer points to the empty object

Function.prototype.b = function() { 
    var a = 20; 
    console.log(this);
	console.log(this.a);
};
var getA = new Function();
getA.b();	// ƒ anonymous() {}
			// undefined

6. When using call or apply, the this pointer points to the situation:

var a = 100;
var obj2 = {
    a: 1111
}
		
var obj1 = {
    a: 100,
	b: 10,
	// 箭头函数在声明时就已经确立了this指针的指向,后续无法更改
	fun: () => { console.log(this.a); },
	// 使用bind声明创建的函数,声明创建完后就已经确立了this指针的指向,后续无法更改
	fun2: (function() { console.log(this.a); }).bind(obj2)
};
		
obj1.fun.call(obj2); // 100
obj1.fun2.call(obj2); // 1111

The function created using the bind statement has established the pointer of this pointer after the statement is created, and cannot be changed later.

7. In the function of the class, the this pointer points to:

class Foo {
    name = "Foo";
	a() { console.log(this.name); };
	b = function() { console.log(this.name) };
	c = () => { console.log(this.name); };
};
let f = new Foo();
f.c();				// Foo
let b = { name: "bar", a: f.a, b:f.b, c: f.c };
b.a();				// bar
b.b();				// bar
b.c();		// Foo  // ES6箭头函数在定义时this指向就绑定了,无法修改。在类中无法穿透

The above is the common this pointer pointing to the problem, but it is not comprehensive.

 

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109397990