2014-04-07 84 views
0

我無法訪問函數中Typescript中的類中聲明的對象。這是我有:無法訪問Typescript中的對象

export class QUestions { 

    credentials:mysqlCredentials.MySQLCredentials; 
    sqlConnector:mysql.Mysql; 

    constructor() { 
     this.credentials = new mysqlCredentials.MySQLCredentials('192.168.249.139', 'dev', 'dev', 'test'); 
     this.sqlConnector = new mysql.Mysql(this.credentials); 
    } 

    addQuestion(req, res) { 
     var q = ...<Lot of code over here> ; 
     this.sqlConnector.query(q, null); //Error shown for this line 
     res.send(); 
    } 
} 

Error: 
TypeError: Cannot call method 'query' of undefined 

如果如上所示即sqlConnector變量在打字稿類定義的代碼的結構,它引發錯誤。如果我將sqlConnector放置在Typescript類之外,它可以正常工作。我需要解決這個問題,因爲我需要類中的sqlConnector對象。

export class Questions { 

    credentials:mysqlCredentials.MySQLCredentials; 

    constructor() { 
     this.credentials = new mysqlCredentials.MySQLCredentials('192.168.249.139', 'dev', 'dev', 'test'); 
     sqlConnector = new mysql.Mysql(this.credentials); 
    } 

    addQuestion(req, res) { 
     var q = ...<Lot of code over here> ; 
     sqlConnector.query(q, null); //Error shown for this line 
     res.send(); 
    } 
} 

var sqlConnector; 

回答

1

你是否在新的上下文中調用類(例如使用事件處理程序)?

如果是這樣,this成爲事件的上下文,而不是類上下文。這也是在TypeScript中可能發生的常見JavaScript問題。

可以解決範圍的問題在許多方面:

用箭頭功能

如果使用箭頭功能將功能分配給對問題類的成員,它總是會使用類範圍。

export class Questions { 

    credentials:mysqlCredentials.MySQLCredentials; 
    sqlConnector:mysql.Mysql; 

    constructor() { 
     this.credentials = new mysqlCredentials.MySQLCredentials('192.168.249.139', 'dev', 'dev', 'test'); 
     this.sqlConnector = new mysql.Mysql(this.credentials); 
    } 

    addQuestion = (req, res) => { 
     var q = ...<Lot of code over here> ; 
     this.sqlConnector.query(q, null); //Error shown for this line 
     res.send(); 
    } 
} 

使用call設置範圍方面

這種替代解決方案意味着問題類並不需要被關注的範圍 - 如果你打電話從不同的作用域上下文的方法,您只需使用call將問題實例指定爲範圍。

element.onclick = function() { 
    questions.addQuestion.call(questions, argA, argB); 
}; 
0

也可以到類實例分配給變量,編譯後仍將模塊範圍內:

var scl:QUestions; 
export class QUestions { 

    credentials:mysqlCredentials.MySQLCredentials; 
    sqlConnector:mysql.Mysql; 

    constructor() { 
     scl = this; 
     this.credentials = new mysqlCredentials.MySQLCredentials('192.168.249.139', 'dev', 'dev', 'test'); 
     this.sqlConnector = new mysql.Mysql(this.credentials); 
    } 

    addQuestion(req, res) { 
     var q = ...<Lot of code over here> ; 
     scl.sqlConnector.query(q, null); 
     res.send(); 
    } 
} 

要知道,雖然,如果你有很多情況下,它可能會引起一些問題單個模塊中的QUestions類。大多數情況下仍然可以正常工作。