Ad

Javascript How To Override A Constructor Method?

- 1 answer

I have a View class that has a constructor method initialize I think this is a constructor method, correct me if wrong.

var View = function(obj) {
    this.initalize = obj.initalize;
};

What I would like to achieve is something gets called when the Class is instantiated.

How can I pass in an object like so?

var chatView = new View({
    initialize: function() {
        alert('Yay for initialization');
    }
});

So that when I instantiate the View I can pass an object to the constructor and within a key initialize which value is a function and this key specifically gets called when instantiated.

Ad

Answer

If I get it right, there is a simple way of achieving what you want:

var View = function(obj) {
    obj.initialize();
}

This way, the initialize function gets called whenever you instantiate a View class.

Be aware that if you want to do real "initialization code" inside the initialize function to work, you could use call (or apply):

var View = function(obj) {
    if (typeof obj.initialize === 'function') {
        obj.initialize.call(this);
    }
}

var chatView = new View({
    initialize: function() {
        this.property = 'property';
    }
});

console.log(chatView.property); // outputs property
Ad
source: stackoverflow.com
Ad