this详解

MDN解释this

当前执行上下文(global、function 或 eval)的一个属性。

在非严格模式下,总是指向一个对象,在严格模式下可以是任意值。

 

全局上下文

无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指向全局对象。

// 在浏览器中, window 对象同时也是全局对象:
可以使用 globalThis 获取全局对象,无论代码是否在当前上下文运行。(Node环境、浏览器环境)

 

函数上下文

在函数内部,this的值取决于函数被调用的方式。

 

类上下文

this 中的表现与在函数中类似,因为类本质上也是函数,但也有一些区别和注意事项。

在类的构造函数中,this 是一个常规对象。类中所有非静态的方法都会被添加到 this 的原型中:

 

派生类

不像基类的构造函数,派生类的构造函数没有初始的 this 绑定。在构造函数中调用 super() 会生成一个 this 绑定,并相当于执行如下代码,Base为基类:

this = new Base();

 

call、apply、bind(es5新增的)

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty

var o = {a:37, f:f, g:g, h:h};

console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty

 

箭头函数

 

作为对象的方法

当函数作为对象里的方法被调用时,this 被设置为调用该函数的对象。

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // 37

 

原型链中的 this

var o = {
  f: function() {
    return this.a + this.b;
  }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

 

getter 与 setter 中的 this

function sum() {
  return this.a + this.b + this.c;
}

var o = {
  a: 1,
  b: 2,
  c: 3,
  get average() {
    return (this.a + this.b + this.c) / 3;
  }
};

Object.defineProperty(o, 'sum', {
    get: sum, enumerable: true, configurable: true});

console.log(o.average, o.sum); // logs 2, 6

作为构造函数

当一个函数用作构造函数时(使用new关键字),它的this被绑定到正在构造的新对象。

 

 

 

posted @   Dz&Ying  阅读(111)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示