描述
this,函数执行的上下文,可以通过apply,call,bind改变this的指向。对于匿名函数或者直接调用的函数来说,this指向全局上下文(浏览器为window,NodeJS为global),剩下的函数调用,那就是谁调用它,this就指向谁。当然还有es6的箭头函数,箭头函数的指向取决于该箭头函数声明的位置,在哪里声明,this就指向哪里
绑定规则
根据不同的使用场合,this有不同的值,主要分为下面几种情况:
- 默认绑定
- 隐式绑定
- new绑定
- 显示绑定
new绑定优先级 > 显示绑定优先级 > 隐式绑定优先级 > 默认绑定优先级
this指向
调用方式 | 非普通模式下 | 严格模式下 | |
---|---|---|---|
普通函数调用 | window | undefined | function fn() { console.log(this) } fn() |
构造函数调用 | 实例对象,原型对象里面的方法也指向实例对象 | function Star(name) { this.name = name; console.log(this); // this指向Star {name: “ldh”} }; Star.prototype.sing = function() { console.log(this); // this指向Star {name: “ldh”} } var ldh = new Star(‘ldh’) ldh.sing(); |
|
对象方法调用 | 该方法所属的对象 | var obj = { SayHello: function() { console.log(this); // this指向obj对象 {SayHello: f} } } obj.SayHello(); |
|
事件绑定方法 | 绑定事件的对象 | var btn = document.getElementById(‘btn’); btn.onclick = function() { console.log(this); // this 指向该元素 } |
|
定时器函数 | window (此时定时器可看成是window.setInterval,故this指向window) |
setInterval(function() { console.log(this); }, 1000) |
|
立即执行函数 (闭包) |
window | undefined | (function() { console.log(this); })() |
箭头函数 | 定义在哪个对象下,就指向哪个对象,如果有嵌套情况,则绑定到最近的一层对象上。 | function Person(behavior) { this.behavior = behavior; this.getBehavior = () => { console.log(this) // 指向Person } } var person = () => { console.log(this) // 指向window } person() |
|
apply\call\bind | 指向传入的第一个参数 |