简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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