2009-11-28 42 views
5

有没有在JavaScript中将私有成员从基类继承到子类的方法?如何在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 
} 

我如何能实现一类般的仿真,就像在其他OOP语言(如C++)。在那里我可以继承私有(保护)的属性?

谢谢 大卫·施雷伯

+0

此模式不添加私人财产。它只在BaseClass函数中添加一个名为privateProperty的局部变量。 – erikkallen 2009-11-28 17:36:00

+1

请参阅http://stackoverflow.com/questions/1437712/how-to-override-private-variable-in-javascript/1438592#1438592对于我对这种语言混蛋的看法;学习JS的语义,而不是模仿C++ – Christoph 2009-11-28 17:43:28

回答

11

使用Douglas Crockfords power constructor pattern(链接到视频),可以实现受保护的变量是这样的:

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; 
} 

注:随着电力构造模式,您不使用new。相反,只需说var new_object = subclass();

+0

非常感谢!与电源构造模式视频的链接对我非常有帮助。这正是我正在寻找的。现在我明白了,还有更多的东西让我学习JS和对象:-) – 2009-11-29 15:57:34

+1

链接已经改变;这里是新的: http://www.yuiblog.com/blog/2006/11/27/video-crockford-advjs/ (原来的链接是第1部分) – 2012-12-01 19:25:21

+1

不应该'secret.privateProperty'成为'secret.protectedProperty'然后私有就像'var privateProperty'一样? – sabgenton 2015-09-30 00:24:18

0

这是不可能的。这不是一个真正的私有财产 - 它只是一个常规变量,它只在定义它的范围内可用。

0

那不能做,但你可以删除的类原型的属性,使之不被继承:

SubClass.prototype.privateProperty = undefined; 

这样,它不会被继承,但是你需要做的为您的基类中的每个“私人”财产。

2

标记您私人变量与某种标记像前面的下划线_ 你知道这是一个私有变量(虽然在技术上它不是)这样

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