简单明了不废话, Javascript函数中的this的指向规则

  1. 用new调用函数, this指向新创建的对象。

  2. 使用call,apply(bind)调用函数, this指向绑定的的对象。

  3. 函数作为某对象的属性调用, this指向这个对象。

  4. 其他情况下, this指向全局对象(严格模式下指向undefined)。

补充: 如果第二条规则绑定的是null或者undefined, 则执行第四条规则; 1-4条规则优先级递减。

var a = 1;
var foo1 = {
  a: 2,
  bar: function(){
    console.log(this.a)
  }
};
var foo2 = {
  a: 3
};
var baz = foo1.bar;
baz() // 1 规则4
foo1.bar() // 2 规则3
foo1.bar.call(foo2) // 3 规则2>规则3
new foo1.bar() // undefined 规则1>规则3

var baz2 = foo1.bar.bind(foo2);
new baz2() // undefined 规则1>规则2

foo1.bar.call(null) // 1 this指向global

参考:You Don't Know JS: this & Object Prototypes

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章