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方法的实现
- 深度拷贝的实现