我JSON配置,如:three.js所創建對象動態
{ shape:[ 'SphereGeometry', [7, 16, 16] ] }
並嘗試加載像模型:
new THREE[shape[0]].apply(this, shape[1])
正如你所看到的「新」和「應用」是不是一個選項在這裏。 有沒有人知道一個技巧或提示我如何解決我的問題在這裏?
預先感謝您。
我JSON配置,如:three.js所創建對象動態
{ shape:[ 'SphereGeometry', [7, 16, 16] ] }
並嘗試加載像模型:
new THREE[shape[0]].apply(this, shape[1])
正如你所看到的「新」和「應用」是不是一個選項在這裏。 有沒有人知道一個技巧或提示我如何解決我的問題在這裏?
預先感謝您。
該解決方案是基於Use of .apply() with 'new' operator. Is this possible?
JSON配置
{ shape: 'SphereGeometry', properties: [ null, 7, 16, 16 ] }
和創建新的對象:
new (Function.prototype.bind.apply(THREE[object.shape], object.properties))
使用。適用()和新一般一起是不是一個漂亮的過程,但這是怎麼回事:
function dynamicShape() {
return THREE[shape[0]].apply(this, shape[1]);
}
dynamicShape.prototype = THREE[shape[0]].prototype;
var sphere = new dynamicShape();
這應該工作。這是一個使用一些示例代碼來呈現的小提琴:http://jsfiddle.net/jcc6zbtn/
下面是使用reviver函數執行此操作的一種方法。其優點是解析過程直接負責實例化正確的對象類型,而不是分兩步進行。
var shapes = { 'Rectangle': Rectangle }, //same as THREE in your code
shapeJson = '{ "shape": ["Rectangle", [2, 4]] }',
shape = shapeFromJson(shapeJson);
console.log(shape);
function instanciate(ctor, args) {
var instance = Object.create(ctor.prototype);
ctor.apply(instance, args);
return instance;
}
function createShape(shape, args) {
return instanciate(shapes[shape], args);
}
function shapeFromJson(json) {
return JSON.parse(json, function (key, val) {
return key? val : createShape(val.shape[0], val.shape[1]);
});
}
function Rectangle(height, width) {
this.height = height;
this.width = width;
}