今天有一个关于 this 的默认绑定:
this 的绑定规则 在 非严格模式下,完全取决于函数的调用位。
默认绑定:this 绑定到全局,即 Window;
例如:
示例一:
function foo(){
console.log(this.a);
};
var a = 2;
foo(); // 2 this 绑定到 Window
示例二:
function foo(){
"use strict";
console.log(this.a);
};
var a = 2;
foo(); // TypeError: this is undefined;
在严格模式下,this 绑定到 undefined;
示例三:
function a(){
funtion b(){
console.log(this);
};
b();
};
a(); // Window
这种情况,如果是 绑定到 a 的话,
function a(){
funtion b(){
this();
};
b();
};
a(); // 会造成死循环,所以是错误的;
原文:https://www.cnblogs.com/xhQ2/p/13095405.html