我在阅读javascript-spessore时遇到了问题; 的问题来自参数与原型之间的关系, 以下是代码片段,我把它放在https://jsfiddle.net/abramhum/wf0vom9x/4/关于javascript的原型和参数
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);
我跑的时候
,错误消息显示“遗漏的类型错误:无法读取属性“原型'未定义',不存在超类的原型。 这似乎是一个错误,但在这本书中没有关于 的任何解释。是否有人知道答案,为什么不正确,以及如何纠正它?非常感谢。
如果你想要类的语法,使用ES6,这也应该做什么? – T4rk1n
您在代码中定义了两次'Class'和'QuadTree'。不要这样做。 (提示:第二个'Class' *声明*被挂起,并用于第一个调用)。如果你从对方那里执行* 2 *片段,它就会起作用。 – Bergi