Lajos Arpad Lajos Arpad - 3 months ago 9
Javascript Question

How to create a self-aware prototype?

In Javascript we often need to use class-like

function
objects. A class-like
function
object often needs public members instead of parameters, but this seems to be too labor-intensive on the long term:

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
}


Instead of this I intend to be able to define things like this:

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
}


How can I achieve this?

Answer

You could use Object.assign for this:

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

Can this be used for private variables?

Yes, like this for example (destructuring assignment):

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

console.log(height);