我读完了“面向对象的 Javascript”。我正在按照此代码“继承”并反对另一个代码:
function deriveFrom(child,parent)
{
if (parent == this)
alert("You can't inherit from self class type")
else
{
var f = function () { }
f.prototype = parent.prototype;
child.prototype = f;
child.prototype._super = f.prototype;
child.constructor = child;
}
}
我遇到的问题是,当我想访问一个没有在子类中定义但在父类中的函数或变量时,例如:
认为 ClassB 构造创建了一个名为 myVar 的 var。
deriveFrom(ClassA,ClassB);
var obj=new ClassA();
这将创建一个原型(prototype)链,如下所示:
obj->原型(prototype)(函数)->原型(prototype)(ClassB)->myVar.
如果我做类似 a.myVar 的事情,我会得到一个未定义的。为什么?书上说 javascript 会通过原型(prototype)寻找 var,直到得到它。所以,首先它会在 obj 处搜索它,没有找到它会得到它的原型(prototype)对象,它是一个函数,它不会找到它,然后它会继续向下到函数原型(prototype),在那里它会找到 myVar。这不就是流程吗?
如果我执行 obj.prototype.myVar,它会找到它 :S。
有人可以帮忙吗?
更新:
function ParentClass()
{
}
ParentClass.prototype.initWithAAndB=function(a, b)
{
this.a = a;
this.b = b;
}
function ChildClass()
{
}
//Inheritance
deriveFrom(ChildClass,ParentClass);
ChildClass.prototype.initWithAAndBAndC=function(a,b,c)
{
this._super.initWithAAndB(a, b);
this.c = c;
}
var a = new ChildClass();
a.initWithAAndBAndC(1, 2, 3);
//This works
a.prototype.initWithAAndB(7, 8);
//This does not work, but as the book I stated before explained the function should be found
a.initWithAAndB(7,8);
最佳答案
每当你对像这样的基本 javascript 设计模式有疑问时,首先要看的是很棒的 Douglas Crockford .在他关于 prototypal inheritance 的文章中他最终提出了以下解决方案:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
您可以将此解决方案与当前实现中的类型检查代码结合使用,但我认为如果这是在您自己的代码中使用的便捷方法,则可能不需要错误检查。
关于Javascript 和原型(prototype)链接(不在原型(prototype)中查找方法和变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3988361/