2013-02-24 83 views
0

我使用私有/公有方法的下一個語法JavaScript調用公共方法中的方法與此指針

function Cars() { 
    this.carModel = ""; 
    this.getCarModel = function() { return this.carModel; } 
    this.alertModel = function() {alert (this.getCarModel());} 
} 

但是,當我打電話給一個方法alertModel其有錯誤,因爲this所指向的對象window因此不能找到它: alert (this.getCarModel()); - this指着窗口

var newObject = new Cars(); 
newObject.alertModel(); 

我想聲明ŧ軟管方法也在prototype,但它的行爲相同。

Cars.prototype.getCarModel = function() { 
    this.getCarModel = function() { return this.carModel; } 
} 
Cars.prototype.alertModel = function() { 
alert (this.getCarModel()); 
} 

什麼I'a做的是調用它沒有這個like是:

Cars.prototype.alertModel = function() { 
    alert (newObject.getCarModel()); 
    } 

是它的唯一途徑?因爲在其他方法中它的作品。

+0

這兩個答案都是題外話。你一定是錯的。在你的例子中,'this'是實例('newObject'),所以它應該將空字符串警告爲'carModel'的值。 – marekful 2013-02-24 09:57:26

+0

@ MarcellFülöp這是我從不同頁面調用它時的行爲... – oleg 2013-02-24 10:02:58

回答

0

試試這個:

function Cars() { 
    this.carModel = ""; 
    this.getCarModel = function() { return this.carModel; } 
    this.alertModel = function() {alert (this.getCarModel());} 

    return { 
    getCarModel: getCarModel, 
    alertModel: alertModel 
    } 
} 

var newObject = new Cars(); 
newObject.alertModel(); 
0

試試這個:

function Cars() { 
    var carModel = ""; 
    this.getCarModel = function() { return carModel; }; 
    this.alertCarModel = function() { alert (carModel) }; 
} 

這樣carModel將是私有,不能僅由alertCarModel和getCarModel方法公開訪問。