2013-06-06 15 views
0

返回塊內我有一個像下面如何使用原型方法的構造

var Example = (function() { 
    function Example(opt) { 
    this.opt = opt; 
    return{ 
     function(){ console.log(this.check()); } // Here is an Error 
    } 
    } 
    Example.prototype.check = function() { 
    console.infor('123'); 
    }; 
    return Example; 
})(); 

var ex = new Example({ a:1 }); 

我知道我做錯了,但找不出來做到這一點的方式構造。我想在對象返回中使用原型方法。請幫助我。

+1

你沒有鑰匙返回一個對象?這看起來不太好...再加上構造函數會返回實例嗎?你準備在那裏做什麼? – elclanrs

回答

2

如果您想在構建實例時運行check(),爲何不在構造函數中調用它?

var Example = (function() { 
    function Example(opt) { 
    this.opt = opt; 
    this.check(); //this gets called when instances are made 
    } 
    Example.prototype.check = function() { 
    console.infor('123'); 
    }; 
    return Example; 
})(); 

//so `ex` is an instance of the Example Constructor 
//and check gets called when you build it 
var ex = new Example({ a:1 }); 
1

function Example(opt) { 
    this.opt = opt; 
    this.check() 
} 
Example.prototype.check = function() { 
    console.info('123'); 
};