JavaScript 访问父作用域

JavaScript access parent scope

我很难弄清楚如何访问父级的 class 范围。我的代码如下

var Class = function(){
    this.smth = 3;
}

Class.prototype.setters = {};
Class.prototype.setters.smth = function(smth){
    this.smth = smth;
}

不过这当然不行,影响smthClass.setters。我尝试使用 .bind(Class.prototype); 无济于事。 有没有人有办法解决吗?我有很多子方法。

您可以通过几种方式做到这一点。还有其他人使用您的原型方法,但这可能会使它更清楚一点:

ES5

var TestClassEs5 = function(){
    // With ES5, store the outer this to variable to preserve
    var self = this;
    this.smth = 3;

    this.setters = {
      smth: function (smth) {
        self.smth = smth;
      }
    }

    return this;
}

ES6

const TestClassEs6 = function(){
    this.smth = 3;

    // Using a fat arrow syntax binds the function to the lexical scope
    this.setters = {
      smth: (smth) => this.smth = smth
    }

    return this;
}

JS斌: http://jsbin.com/qugatacive/edit?js,console

当您调用 someInstance.setters.smth(...) 时,函数调用的 thissettings 对象,smth 函数无法知道 如何 settings 对象被访问,只是它作为 this.

提供

通过在构造函数中为每个实例创建一个唯一的 setters 对象,您可以保留所需的语法,但内存成本很高:

var Class = function(){
    var thisClassInstance = this;
    this.smth = 3;
    this.setters = {};
    this.setters.smth = function(smth){
        thisClassInstance.smth = smth;
    }
}

这是次优的,因为你失去了原型继承的好处;每个实例在 setters 对象中都有一套独特的功能,没有任何共享。

一种更精简的方法是让每个实例都有自己的 setters 对象,该对象知道其父实例的身份,但是 setters 对象从原型继承其所有方法 setter 对象:

// all `setters` object inherit their methods from this object
var settersPrototype = {};

// methods on the `setters` set values on `this.parent`
settersPrototype.smth = function(smth){
    this.parent.smth = smth;
}

var Class = function(){
    this.smth = 3;

    // this instance has a `setters` object that inherits all its methods
    this.setters = Object.create(settersPrototype);
    this.setters.parent = this;
}

这样,每个实例的唯一 { parent: ... } 对象的内存开销很小,但是每个 setter 函数都有一个原型版本,存在于唯一 settersPrototype对象。