他山之石,可以攻玉——匿名reference type: this

1. thismethod

let user={
  name: "Jason",
  showName() { alert(this.name); }
}
alert(user.showName()); //Jason

定义在对象内部的function,我们称作method。method往往需要access对象的其他property,往往是data, 这个时候就需要this关键字,在method内部通过this.propertyName来获取。

this的其他用法:

this的用法非常广泛,它完全可以被应用在任何函数的内部,不仅仅限于method,在C++或者其他一些语言中,this和对象是捆绑的(bound),但在JS中不是这样。this指向的对象由函数运行环境(execution context)决定。this的维基介绍

2. 调用method的方式

有this信息的调用方式:

user.showName();
user["showName"]();

复杂的调用方式很有可能丢失了this信息,比如:

(method=user.showName)();

这是因为:dot operator .返回的是Reference Type, 里面包含了(base,name, strict)信息
base is the object.
name is the property.
strict is true if use strict is in effect.
当我们对Reference Type进一步做其他运算,然后再(),Reference Type转换成了function,丢失了base/object信息。

3. return this实现chained method calls

let obj={
  step: 0,
  up() {
    this.step++;
    return this;
  },
  down() {
    this.step--;
    return this;
  },
  showStep() {
    alert(this.step);
  }
}

obj.up().down().up().showStep(); //1
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容