2015-10-09 60 views
0

試圖去掌握來自c#背景的面向對象的原型香草JavaScript繼承。Javascript原型繼承基礎函數undefined

我有一個基地「類」,做一個HTTP GET。我想從此繼承,以便子類可以封裝此HTTP GET的變體。

在下面的代碼中,我得到getUser函數中的一個httpGet is undefined錯誤。我的最終目標是獲得一個不錯的簡單方法的調用,如userComms.getUser()

// declare base class 
function HttpComms() { } 
HttpComms.prototype.httpGet = function (url, callback) { 
    // Code to do http get request 
}; 

// declare sub class 
function UserComms() { 
    this.getUser = function() { 
     // error thrown here: 
     httpGet('user/get', function (data) { 
      console.log(data); 
     }); 
    } 
} 
// hookup prototypal relationship between base and sub 
UserComms.prototype = Object.create(HttpComms.prototype); 

// create and call sub class. 
var userComms = new UserComms(); 
userComms.getUser(); 

爲什麼我得到的錯誤,什麼是最靈活的方式來得到這個工作?

回答

3

this.httpGet面前:

function UserComms() { 
    this.getUser = function() { 
     // error thrown here: 
     this.httpGet('user/get', function (data) { 
      console.log(data); 
     }); 
    } 
}