带有特权函数的Javascript继承
我正在简化我的例子,以触及我问题的核心。我有一个带有特权函数的Javascript基类。我真的需要隐藏myVar以防被看到,我还真的想从基类继承 我遇到的问题是,我试图这样继承:带有特权函数的Javascript继承,javascript,inheritance,prototypal-inheritance,Javascript,Inheritance,Prototypal Inheritance,我正在简化我的例子,以触及我问题的核心。我有一个带有特权函数的Javascript基类。我真的需要隐藏myVar以防被看到,我还真的想从基类继承 我遇到的问题是,我试图这样继承: function childClass() { } childClass.prototype = new baseClass(); childClass.prototype.reallyCoolFunction = function() {//Really cool stuff} 但只会创建一个myVar实例,这将
function childClass() {
}
childClass.prototype = new baseClass();
childClass.prototype.reallyCoolFunction = function() {//Really cool stuff}
但只会创建一个myVar实例,这将不起作用,因为coolClass具有依赖于实例的属性。
因此,如果我这样做:
var x = new childClass();
var y = new childClass();
x和y都将具有相同的baseClass.myVar实例
据我所知,我有两个选择:
使myPrivileged函数成为原型函数并公开myVar
将基类的内部复制粘贴到childClass中,这让我很想插嘴
我不是javascript大师,所以我希望有人能想出一个好主意
首先,您不需要仅仅为了设置继承而创建基类实例。您正在创建一个从未使用过的coolClass实例。使用代理构造函数
function childClass() {
...
}
function surrogateCtor() {
}
surrogateCtor.prototype = baseClass;
childClass.prototype = new surogateCtor();
function childClass() {
baseClass.call(this);
}
在子类中,需要调用父类的构造函数
function childClass() {
...
}
function surrogateCtor() {
}
surrogateCtor.prototype = baseClass;
childClass.prototype = new surogateCtor();
function childClass() {
baseClass.call(this);
}
这将确保每次实例化子类时都初始化基类
查看我在JS中关于继承的帖子你应该看看@Kyle:你至少应该为你的评论写一些理由。大多数人不愿意开始使用编译成JS的语言,因此无法调试。@JuanMendes无法调试?不,不是真的。这只是你的意见。@Kyle你的评论只是一个评论。CoffeeScript似乎很有用,但似乎根本没有解决我的问题。@Kyle除了使用console.log外,您如何调试CoffeeScript中的代码?