THREE.JS动态创建对象

时间:2014-10-07 19:40:44

标签: javascript three.js

我有JSON配置,如:

{ shape:[ 'SphereGeometry', [7, 16, 16] ] }

并尝试加载模型:

new THREE[shape[0]].apply( this, shape[1] )

正如你所看到的那样" new"并且"申请"这里不是一个选择。 有谁知道如何在这里解决我的问题的技巧或提示?

提前谢谢。

3 个答案:

答案 0 :(得分:0)

解决方案基于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 ))

答案 1 :(得分:0)

一般情况下使用.apply()和new并不是一个很好的过程,但这是如何进行的:

function dynamicShape() {
    return THREE[shape[0]].apply(this, shape[1]);
}
dynamicShape.prototype = THREE[shape[0]].prototype;

var sphere = new dynamicShape();

这应该有效。这是一个使用一些示例代码进行渲染的小提琴:http://jsfiddle.net/jcc6zbtn/

答案 2 :(得分:0)

这是使用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;
}