关于 JavaScript-from Book [JavaScript-Spessore] 中的原型和参数



我在阅读javascript-spessore时遇到问题; 问题来自参数和原型之间的关系, 以下是代码片段,我把它放在 https://jsfiddle.net/abramhum/wf0vom9x/4/

function Class() {
return {
create: function() {
var instance = Object.create(this.prototype);
Object.defineProperty(instance, 'constructor', {
value: this
});
if (instance.initialize) {
instance.initialize.apply(instance, arguments);
}
return instance;
},
defineMethod: function(name, body) {
this.prototype[name] = body;
return this;
},
prototype: {}
};
}
var QuadTree = Class();
QuadTree.defineMethod(
'initialize',
function(nw, ne, se, sw) {
this.nw = nw;
this.ne = ne;
this.se = se;
this.sw = sw;
}
).defineMethod(
'population',
function() {
return this.nw.population() + this.ne.population() +
this.se.population() + this.sw.population();
}
);
var BasicObjectClass = {
prototype: {}
}
function Class(superclass) {
return {
create: function() {
var instance = Object.create(this.prototype);
Object.defineProperty(instance, 'constructor', {
value: this
});
if (instance.initialize) {
instance.initialize.apply(instance, arguments);
}
return instance;
},
defineMethod: function(name, body) {
this.prototype[name] = body;
return this;
},
prototype: Object.create(superclass.prototype)
};
}
var QuadTree = Class(BasicObjectClass);

当我运行时,错误消息显示"未捕获的类型错误:无法读取未定义的属性'原型'",不存在超类的原型。 这似乎是一个错误,但在 这本书。有没有人知道答案,为什么它不正确,以及如何 纠正吗?多谢。

由于功能提升,您陷入了麻烦。您定义了两个不同的函数:

function Class()

当你这样做时,javascript将这些"提升"到顶部,这意味着第二个总是被调用。所以你第一次打电话...

var QuadTree = Class();

。您实际上是在调用第二个函数。由于您没有传递参数,因此参数superclass是未定义的。这就是为什么重用函数名称是一个坏主意的原因。

将第一个函数重命名为Class1()并将调用更改为var QuadTree = Class1()会使错误消失。

最新更新