1

是否有任何动态方式来转换/克隆此对象:

var object = {
    a: 2,
    b: function(){
         return this.a;
    }
}

进入这种函数对象:

function object(){};

object.a = 2;
object.b = function(){
    return this.a;
};

这可能吗?我怎样才能动态地做到这一点?

4

2 回答 2

2

You can just copy everything, though I would use the prototype:

function toClass(obj) {
    var func = function () {};
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            func.prototype[i] = obj[i];
        }
    }

    return func;
}

A whole other question is how useful this actually is and whether there is a better solution to the underlying problem.

Fiddle: http://jsfiddle.net/pb8mv/

于 2013-08-29T19:07:25.993 回答
0

你需要这样的东西有点奇怪。如果我不得不猜测,我认为你有一个对象并且你想扩展它。即您想基于该对象创建函数,因此您稍后会创建它的多个实例。这是可能的,这里有一个小片段显示如何:

var object = {
    a: 2,
    b: function(){
         return this.a;
    }
}
var extend = function(obj) {
    return function() {
        return Object.create(obj);
    }
};

var Class1 = extend(object);
var ob1 = Class1();
ob1.a = 10;

var Class2 = extend(object);
var ob2 = Class2();
ob2.a = 23;

console.log(ob1.b(), ob2.b());

脚本的结果是

10 23
于 2013-08-31T08:18:14.760 回答