简体   繁体   English

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

[英]How to inherit a private member in JavaScript?

is there a way in JavaScript to inherit private members from a base class to a sub class? 在JavaScript中有一种方法可以将私有成员从基类继承到子类吗?

I want to achieve something like this: 我希望实现这样的目标:

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
}

How can I achieve a class-like simulation, like in other oop-languages (eg. C++) where I can inherit private (protected) properties? 我怎样才能实现类似于类的模拟,就像我可以继承私有(受保护)属性的其他oop语言(例如C ++)一样?

Thank you, David Schreiber 谢谢David Schreiber

Using Douglas Crockfords power constructor pattern (link is to a video), you can achieve protected variables like this: 使用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;
}

Note: With the power constructor pattern, you don't use new . 注意:使用电源构造函数模式,您不使用new Instead, just say var new_object = subclass(); 相反,只需说var new_object = subclass(); .

Mark your private variables with some kind of markup like a leading underscore _ This way you know it's a private variable (although technically it isn't) 使用某种标记(如前导下划线)标记您的私有变量_这样您就知道它是一个私有变量(虽然从技术上讲它不是)

this._privateProperty = "private";
alert( this._privateProperty )

This isn't possible. 这是不可能的。 And that isn't really a private property - it's simply a regular variable that's only available in the scope in which it was defined. 这不是一个真正的私有财产 - 它只是一个常规变量,只能在定义它的范围内使用。

That can't be done, but you could delete the property from the class prototype so that it is not inherited: 这是不可能的,但您可以从类原型中删除该属性,以便它不会被继承:

SubClass.prototype.privateProperty  = undefined;

That way it won't be inherited, but you need to do that for every "private" property in your base class. 这样它就不会被继承,但你需要为你的基类中的每个“私有”属性做这件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM