如何在JavaScript中继承私有成员?

dav*_*ber 6 javascript inheritance private-members

在JavaScript中有一种方法可以将私有成员从基类继承到子类吗?

我希望实现这样的目标:

function BaseClass() {
  var privateProperty = "private";

  this.publicProperty = "public";
}

SubClass.prototype = new BaseClass();
SubClass.prototype.constructor = SubClass;

function SubClass() {
  alert( this.publicProperty );   // This works perfectly well

  alert( this.privateProperty );  // This doesn't work, because the property is not inherited
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现类似于类的模拟,就像我可以继承私有(受保护)属性的其他oop语言(例如C++)一样?

谢谢David Schreiber

Mag*_*nar 13

使用Douglas Crockfords电源构造函数模式(链接到视频),您可以实现这样的受保护变量:

function baseclass(secret) {
    secret = secret || {};
    secret.privateProperty = "private";
    return {
        publicProperty: "public"
    };
}

function subclass() {
    var secret = {}, self = baseclass(secret);
    alert(self.publicProperty);
    alert(secret.privateProperty);
    return self;
}
Run Code Online (Sandbox Code Playgroud)

注意:使用电源构造函数模式时,不要使用new.相反,只是说var new_object = subclass();.

  • 不应该`secret.privateProperty`是`secret.protectedProperty`然后私有就像`var privateProperty`? (2认同)