你不知道的JS系列上( 45 ) - 隐式混入

var Something = {
  cool: function () {
    this.greeting = 'Hello World';
    this.count = this.count ? this.count + 1 : 1;
  }
}
Something.cool();
Something.greeting; // 'Hello World'
Something.count; // 1

var Another = {
  cool: function() {
    // 隐式把 Something 混入 Another
    Something.cool.call(this);
  }
};
Another.cool();
Another.greeting; // 'Hello World'
Another.count; // 1

通过在构造函数调用或者方法调用中使用 Something.cool.call(this); 实际上 “借用” 了函数 Something.cool() 并在 Another 的上下文调用了它。最终的结果是 Something.cool() 中的赋值操作都会应用到 Another 对象。因此,我们把 Something 的行为 “混入” 到了 Another 中。

虽然这类技术利用了 this 的重新绑定功能,大师 Something.cool.call(this) 仍然无法变成相对而且更灵活的引用,所以使用时千万要小心。通常来说,尽量避免这样的结构,以保证代码的整洁和可维护性。

猜你喜欢

转载自www.cnblogs.com/wzndkj/p/12651165.html
45