【发布时间】:2010-10-21 14:10:54
【问题描述】:
我读完了“面向对象的 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;
}
}
我遇到的问题,是当我想访问子类中没有定义但在父类中的函数或var时,例如:
认为 ClassB 构造创建了一个名为 myVar 的 var。
deriveFrom(ClassA,ClassB);
var obj=new ClassA();
这样创建了一个原型链:
obj->原型(函数)->原型(ClassB)->myVar.
如果我执行类似 a.myVar 的操作,我会得到一个未定义的结果。为什么?这本书指出,javascript 将通过原型寻找 var 直到它得到它。所以,首先它会在 obj 中搜索它,没有找到它会得到它的原型对象,它是一个函数,它不会找到它,然后它会继续向下进入函数原型,在那里它会找到 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);
【问题讨论】:
-
你从哪里得到的代码?我不认为这是正确的;例如,如果您只是将其称为全局函数(因为“this”将始终是全局上下文),那么对“this”的测试并没有真正意义。一般来说,我见过这样的“deriveFrom”函数被写成添加到
Function.prototype。
标签: javascript