什么时候用this?
//构造函数 new 原型
会发现new会改变this指向,并且优先级最高
//bind call apply
这三也可以改变this指向
//对象
谁调用指向谁
//函数
this的指向window 因为在执行期上下文中,
由于没人调用,所有会有一个默认绑定
this ==》window
总结:
默认绑定: this ==》window
隐试绑定: 谁调用指向谁
显示绑定: bind apply call
new 改变this指向!!!
var module = {
x: 42,
getX: function() {
return this.x;
}
}
var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42