Конструктор или функция init для объекта
Я искал конструктор или функцию init для следующей ситуации:
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
};
Abc.prototype.init = function(){
// Perform some operation
};
//Creating a new Abc object using Constructor.
var currentAbc = new Abc(obj,obj);
//currently I write this statement:
currentAbc.init();
Есть ли способ вызвать функцию init при инициализации нового объекта?
Ответы
Ответ 1
Вы можете просто вызвать init()
из функции конструктора
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
};
Вот скрипка, демонстрирующая: http://jsfiddle.net/CHvFk/
Ответ 2
Возможно, что-то вроде этого?
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init = function(){
// Do things here.
}
this.init();
};
var currentAbc = new Abc(obj,obj);
Ответ 3
если ваш метод init должен оставаться закрытым:
var Abc = function(aProperty,bProperty){
function privateInit(){ console.log(this.aProperty);}
this.aProperty = aProperty;
this.bProperty = bProperty;
privateInit.apply(this);
};
Мне нравится это больше.
Ответ 4
Как насчет этого?
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
//init
(function () {
// Perform some operation
}.call(this));
};
var currentAbc = new Abc(obj,obj);
Ответ 5
Почему бы не поместить материал в функцию init в cunstructor, например:
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
// Perform some operation
};