Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  84] [ 6]  / answers: 1 / hits: 10264  / 9 Years ago, mon, january 25, 2016, 12:00:00

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.


More From » oop

 Answers
2

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

[#31348] Friday, January 22, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiej

Total Points: 294
Total Questions: 95
Total Answers: 97

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;