JavaScript OOP修复了这个范围

javascript oop with fixed this scope?

本文关键字:范围 OOP JavaScript      更新时间:2024-01-15

我正在尝试在javascript中实现一些基本的面向对象,如下所示:

function Cat(name) {
  this.name = name;
}
Cat.prototype.sayName = function() {
  console.log(this.name);
};
Cat.prototype.fetchCat = function() {
  someAsyncCall()
      .success(this.sayName)
      .error(someOtherMethod);
};

someAsyncCall完成后sayName被调用,但this范围不是我所期望的。我可以通过绑定来解决它:

Cat.prototype.fetchCat = function() {
  someAsyncCall()
      .success(this.sayName.bind(this))
      .error(someOtherMethod.bind(this));
};

有没有一些语法上"更好"的解决方案,而不是在回调时必须记住一直.bind

Cat.prototype.fetchCat = function() {
var self = this;
  someAsyncCall()
      .success(function(){self.sayName})
      .error(someOtherMethod);
};

参考Airbnb的javascript指南行,

// bad
function() {
  var self = this;
  return function() {
    console.log(self);
  };
}
// bad
function() {
  var that = this;
  return function() {
    console.log(that);
  };
}
// good
function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
}

ECMA-262 没有对下划线进行任何特殊处理,并说:

美元符号 ($( 和下划线 (_( 允许在 标识符名称。

但是由于JavaScript作为一种语言不支持开箱即用的封装,因此"_"约定旨在指示变量是"私有的"或不应在外部使用。