JavaScript 中的 this 是什么?
- 如果这个函数是
function#bind调用的结果,那么this指向的是传入bind的参数 - 如果函数是以
foo.func()形式调用的,那么this值为foo - 如果是在严格模式下,
this将为undefined - 否则,
this将是全局对象(浏览器环境里为window)
class Foo {
x = 3;
print() {
console.log('x is ' + this.x);
}
}
var f = new Foo();
f.print(); // Prints 'x is 3' as expected
// Use the class method in an object literal
var z = { x: 10, p: f.print };
z.p(); // Prints 'x is 10'
var p = z.p;
p(); // Prints 'x is undefined'
Written on Feb 10, 2019