1、默认绑定
默认绑定通常是指函数独立调用,不涉及其他绑定规则。非严格模式下,this指向window,严格模式下,this指向undefined。
01、题目1.1:非严格模式
var foo = 123;
function print(){
this.foo = 234;
console.log(this); // window
console.log(foo); // 234
}
print();
非严格模式,print()为默认绑定,this指向window,所以打印window和234。
这个foo值可以说道两句:如果学习过预编译的知识,在预编译过程中,foo和print函数会存放在全局GO中(即window对象上),所以上述代码就类似下面这样:
window.foo = 123
function print() {
this.foo = 234;
console.log(this);
console.log(window.foo);
}
window.print()
02、题目1.2:严格模式
把题目1.1稍作修改,看看严格模式下的执行结果。
"use strict"可以开启严格模式
“use strict”;
var foo = 123;
function print(){
console.log('print this is ', this);
console.log(window.foo)
console.log(this.foo);
}
console.log('global this is ', this);
print();
注意事项:开启严格模式后,函数内部this指向undefined,但全局对象window不会受影响
答案
global this is Window{…}
print this is undefined
123
Uncaught TypeError: Cannot read property ‘foo’ of undefined
03、题目1.3:let/const
let a = 1;
const b = 2;
var c = 3;
function print() {
console.log(this.a);
console.log(this.b);
console.log(this.c);
}
print();
console.log(this.a);
let/const定义的变量存在暂时性死区,而且不会挂载到window对象上,因此print中是无法获取到a和b的。
答案
undefined
undefined
3
undefined
04、题目1.4:对象内执行
a = 1;
function foo() {
console.log(this.a);
}
const obj