【发布时间】:2010-10-30 05:17:54
【问题描述】:
我知道有很多类似的问题对此有很多很好的答案。我试图查看经典的继承方法或那些闭包方法等。不知何故,我认为它们或多或少对我来说是“hack”方法,因为它并不是 javascript 的设计目的。 (如果我错了,欢迎任何人纠正我)。 好的,只要它有效,我对经典的继承模式感到满意,例如:
PARENTClass = function (basevar) { do something here; };
PARENTClass.prototype = { a: b, c: d}; // prototype is auto gen
// Inheritance goes here
CHILDClass = function (childvar) { do something; };
CHILDClass.prototype = new PARENTClass(*1); // Actual inheritance to the prototype statement
// Instance
CHILDInstance = new CHILDClass(whatever);
以上是我理解的 JS 的继承。但是我不知道如何实现的一种情况是,如果我想在对象创建期间(即在构造函数中)进行一些初始化,并且可以立即使用新对象......我对问题的说明可能不是说得太清楚了,所以让我用下面的 C# Psuedo 来解释我想要做什么:
class PARENT {
public PARENT (basevar) { ... }
}
class CHILD : PARENT {
public CHILD (basevar) : PARENT (basevar) // constructor of child, and call parent constructor during construct.
{ ... }
}
出于某种原因(如 init.UI 元素),将它们放在构造函数中似乎是最好的方法。任何人都知道我该怎么做。
PS:在 *1 中,我不知道应该放什么。 PS2:上述情况我DID发现jquery.inherit库可以做到,不知道不使用库能不能实现。 PS3:或者我的理解是错误的。由于 javascript 不是为了模仿 OOP(这就是我称之为 hack 的原因),所以实现这一点的“正确”逻辑是什么。
【问题讨论】:
-
使用 Object.create() 从基类继承原型。这种方式对基类的更改会影响到子类,而不是相反。更多详情见我的博客:ncombo.wordpress.com/2013/07/11/…