我在阅读 javascript-spessore 时遇到问题; 问题来自于参数和原型(prototype)之间的关系, 下面是代码片段,我把它放在 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);
当我运行时,错误消息显示“Uncaught TypeError: Cannot read property 'prototype' of undefined”,不存在父类(super class)的原型(prototype)。 这似乎是一个错误,但没有任何解释 这本书。有谁知道答案,为什么不正确,以及如何解决 纠正它吗?非常感谢。
最佳答案
由于函数提升,您陷入了麻烦。您定义了两个不同的函数:
function Class()
当您执行此 JavaScript 操作时,会将这些“提升”到顶部,这意味着始终会调用第二个。所以当你第一次打电话时......
var QuadTree = Class();
…您实际上正在调用第二个函数。由于您没有传递参数,因此参数 superclass
未定义。这就是为什么重复使用函数名称不是一个好主意。
将第一个函数重命名为 Class1()
并将调用更改为 var QuadTree = Class1()
可使错误消失。
关于javascript - 关于javascript中的原型(prototype)和参数-来自书籍[javascript-spessore],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179974/