What is the benefit of using extend on the prototype in three.js inheritance pattern?

匿名 (未验证) 提交于 2019-12-03 01:01:02

问题:

Working with the excellent Three.js framework and currently looking for a good javascript inheritance pattern, I had a look to what is done in Three.js. I now have a good understanding of what's going on, except for some "class" such as Vector3.

Especially, it's not clear for me, why some methods are directly added to the prototype and some are added using THREE.extend in the same "class", like following :

... 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 () {...}(),     ... } 

What's the benefit to use extends, whereas it's possible to augment the prototype object ?

Edit

The code sample is part of the same file, see https://github.com/mrdoob/three.js/blob/master/src/math/Vector3.js I'm not asking what are the differences between the two parts, but why extend is used just after defining the prototype. Or in other words (with the previous extract), why not just write :

... THREE.Vector3.prototype = {     setX: function ( x ) {          this.x = x;          return this;      },     applyEuler: function () {...}(), ... }; 

回答1:

Why are some methods directly added to the prototype and some are added using THREE.extend

Seriously, it doesn't make any sense.

As you can find out in the blame view, @mrdoob introduced this oddity with revision cc57273. The commit message says:

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.

This is reverting commit e2df06e by @bhouston where extend was introduced:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!