three.js源碼中存在大量的copy方法,clone方法,例如:
1.源碼截圖
在copy方法也存在着遞歸調用,例如:
2.代碼結構
function Object3D() {
}
// recursive: 英文是遞歸的意思
Object3D.prototype = Object.assign({}, {
constructor: Object3D,
isObject3D: true,
add: function() {},
clone: function (recursive) {
return new this.constructor().copy(this, recursive);
},
copy: function (source, recursive) {
if (recursive === undefined) {
recursive = true;
}
this.name = source.name
this.userData = JSON.parse(JSON.stringify(source.userData))
if (recursive === true) {
for (var i = 0; i < source.children.length; i++) {
var child = source.children[i];
this.add(child.clone()); // 此處有遞歸調用
}
}
// ... 其他代碼
}
})
3.總結
- new this.constructor()的使用,也就是調用構造函數,進行執行個體化對象
- copy方法的實作
- 深度拷貝的實作