js in this mechanism
Neither point where this function itself, does not refer to the lexical scope of a function, in time this function is called to determine, it all depends on the point where the function call, rather than this being declared
(except arrow function): What this particular point, depending on how you function call. That who call this, this points to who
- Global function in this
function demo() {
alert(this); // this -> window
}
demo();
In strict mode this is undefined
function demo() {
'use strict';
alert(this); // undefined
}
demo();
- The method object, the method calls whom, the method of this points to who
let name = 'finget'
let obj = {
name: 'FinGet',
getName: function() {
alert(this.name);
}
}
obj.getName(); // FinGet
let fn = obj.getName;
fn(); //finget this -> window
- Element Binding event after event is triggered, the function execution of this, points to the current element
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.onclick = function(){
alert(this); // this -> 当前触发
}
}
- Timer in this, pointing to a window
setTimeout(function() {
alert(this); // this -> window ,严格模式 也是指向window
},500)
- When a function call, preceded by the new keyword
function demo() {
//alert(this); // this -> object
this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'
- this points to a problem
var a = 1;
function printA() {
console.log(this.a);
}
var obj = {
a: 2,
foo: printA,
bar: function() {
printA();
}
}
obj.foo(); // 2
obj.bar(); // 1
var foo = obj.foo;
foo(); // 1
//this的指向不是函数声明时绑定的,而是在函数运行过程中动态绑定的
function a(num) {
this.x = num;
return this;
var x = a(5);
var y = a(6)
console.log(x.x); //undefined
console.log(y.x); //6
/*
var x=a(5)
函数内部执行window.x=5
return window
此时window.x=window 而不是5了
var y=a(6)
window.x=6
此时打印x.x 就相当于window.x.x window.x=6 6是没有x属性的 所以undefined
而y此时等于window y.x===window.x ==6
*/
// 匿名函数中的this指向全局对象
var a = 2;
var func = {
a: 4,
fn: (function() {
console.log(this); // window
console.log(this.a); // 2
})()
}
var x = 20;
var a = {
x: 15,
fn: function() {
var x = 30;
return function() {
return this.x
}
}
}
console.log((a.fn())());
//()()自治性函数中的this都是window 所以是20
console.log(a.fn()());
//a.fn()执行放回一个方法 然后加个括号返回的方法执行 此时的this是window 20
console.log(a.fn()() == (a.fn())());
//通过上面两个比较式一样的 true
console.log(a.fn().call(this));
//call this指的是window 20
console.log(a.fn().call(a));
//15
this binding priorities: Priority: new bindings> Show Binding> implicit binding> default binding
new bindings: There are new function calls, this is bound to the newly created object
Show Binding: there are functions bind, apply, call to call, this is bound to the specified object
implicit binding: whether to call in a certain context object function, this is bound to a context object that
default binding: in strict mode, it is bound to undefined, otherwise bound to the global object