如何创建一个自我感知的原型?

时间:2016-08-28 13:31:54

标签: javascript

在Javascript中,我们经常需要使用类似function的类对象。类似function类的对象通常需要公共成员而不是参数,但从长远来看,这似乎是劳动密集型的:

function MyClassLikeFunction(params) {
    this.width = (params.width === undefined) ? 50 : params.width;
    this.height = (params.height === undefined) ? 50 : params.height;
    this.name = (params.name === undefined) ? "foobar" : params.name;
    //And a lot of these initializations and some function definitions
}

而不是这个我打算能够定义这样的事情:

function MyClassLikeFunction(params) {
    //something to enable the behavior
    this.initialize("width", 50);
    this.initialize("height", 50);
    this.initialize("name", "foobar");
    //And a lot of these initializations and some function definitions
}

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用Object.assign

function MyConstructor(params) {
    Object.assign(this, {
        // defaults:
        width: 50,
        height: 50,
        name: 'foobar'
    }, params);    
}

var obj = new MyConstructor( {width: 100, height: 51} );

console.log(obj);

这可以用于私有变量吗?

是的,例如这样(解构分配):

var {height, width, name} = Object.assign({
    width: 50,
    height: 50,
    name: 'foobar'
}, params);    

console.log(height);

答案 1 :(得分:-1)

让我们考虑一下这个原型:

function Initializable(params) {
    this.initialize = function(key, def, private) {
        if (def !== undefined) {
            (!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
        }
    };
}

有了这个,我们就可以定义原型的公共或私人成员。例如:

function MyPrototype(params) {
    Initializable.call(this, params);
    this.initialize("width", 50);
    this.initialize("height", 50);
    this.initialize("name", "foobar");
    //And a lot of these initializations and some function definitions
}