2012-02-14 36 views
15

tôi đang tìm kiếm một nhà xây dựng hoặc một hàm init cho sau tình huống:Constructor hoặc init chức năng cho một đối tượng

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

Có cách nào để gọi hàm init khi đối tượng mới được khởi tạo?

+1

Đặt nó vào trong contructor. –

Trả lời

17

Bạn chỉ có thể gọi init() từ hàm constructor

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 
    this.init(); 
}; 

Đây là một Thể hiện fiddle: http://jsfiddle.net/CHvFk/

+3

Hạn chế tôi thấy trong mẫu này là init là công khai. Nó có thể được gọi là a.init(). Các hàm init thông thường là riêng tư. Vì vậy, nó có thể là tốt để xác định nó trong constructor. Xem [cập nhật fiddle] (http://jsfiddle.net/CHvFk/126/) – Buzut

11

Có lẽ một cái gì đó như thế này?

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

Điều này là đúng, bạn phải gọi hàm init() SAU KHI bạn xác định nó. – Wes

-4

Tại sao không đưa những thứ trong hàm init để cunstructor, như thế này:

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    // Perform some operation 

}; 
+1

Tại sao các chức năng được sử dụng? Để giảm sự dư thừa và tính mô đun của mã của bạn. Đó là lý do tại sao tôi muốn nó như một chức năng. – emphaticsunshine

4

nếu phương pháp init của bạn nên được giữ kín:

var Abc = function(aProperty,bProperty){ 
    function privateInit(){ console.log(this.aProperty);} 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    privateInit.apply(this); 
}; 

tôi thích hơn này.

0

Điều này thì sao?

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    //init 
    (function() { 
     // Perform some operation 
    }.call(this)); 
}; 
var currentAbc = new Abc(obj,obj); 
Các vấn đề liên quan