简体   繁体   English

如何将对象文字转换为函数

[英]How to convert object literal to function

Is there any dynamic way to convert/clone this object: 是否有任何动态方式来转换/克隆此对象:

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

Into this kind of function object: 进入这种功能对象:

function object(){};

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

Is this possible? 这可能吗? how can I do so dynamically? 我该如何动态地这样做?

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/ 小提琴: http : //jsfiddle.net/pb8mv/

It is a little bit strange that you need such a thing. 您需要这样的东西有点奇怪。 If I have to guess, I think that you have an object and you want to extend it. 如果我不得不猜测,我认为您有一个对象,并且想要扩展它。 Ie you want to create function based on that object, so you later create multiple instances of it. 也就是说,您想基于该对象创建函数,因此您稍后将创建该对象的多个实例。 That's possible and here it is a little snippet showing how: 这是可能的,这里有一个小片段显示了如何:

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());

The result of the script is 该脚本的结果是

10 23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM