使用优秀的 Three.js 框架,目前正在寻找良好的 javascript 继承模式,我了解了 Three.js 中所做的事情。 我现在对正在发生的事情有了很好的了解,除了一些“类”,例如 Vector3。
特别是,我不清楚为什么有些方法是直接添加到原型(prototype)中,而有些方法是在同一个“类”中使用 THREE.extend 添加,如下所示:
...
THREE.Vector3.prototype = {
setX: function ( x ) {
this.x = x;
return this;
},
...
};
//and then later in the same file
THREE.extend( THREE.Vector3.prototype, {
applyEuler: function () {...}(),
...
}
使用扩展有什么好处,而可以扩充原型(prototype)对象?
编辑
代码示例是同一文件的一部分,请参阅https://github.com/mrdoob/three.js/blob/master/src/math/Vector3.js 我不是问这两部分有什么区别,而是问为什么在定义原型(prototype)之后就使用extend。 或者换句话说(使用前面的摘录),为什么不直接写:
...
THREE.Vector3.prototype = {
setX: function ( x ) {
this.x = x;
return this;
},
applyEuler: function () {...}(),
...
};
最佳答案
Why are some methods directly added to the prototype and some are added using THREE.extend
说实话,这没有任何意义。
正如您可以在 blame view 中找到的那样,@mrdoob 用 revision cc57273 介绍了这个奇怪的现象。 。提交消息显示:
Reverting to Object.prototype = { pattern. Only using it on the methods that really need it.
Misteriously when using the latest version of the lib on the project I'm working on I'm getting this error:
> Uncaught TypeError: Object [object Object] has no method 'set'
This is caused when THREE.UniformsLib.common.diffuse initialises a THREE.Color (THREE.Color.set() seems to be undefined then). For some reason this only happens when I load Box2D before three.js. If I load it after is all good. But this fixes the problem too.
这正在恢复 commit e2df06e作者:@bhouston,其中引入了 extend
:
fix three missed conversions to closures. switch to extending math prototypes rather than replacing them. This is to ensure that types created in closures within a type's prototype definition get their prototype updated with the full definition.
关于javascript - 在 Three.js 继承模式中对原型(prototype)使用扩展有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21533862/