我在那裏我得到一個錯誤,指出的問題...遺漏的類型錯誤:對象沒有方法...的Javascript
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
我真的不知道是什麼導致了這一點。 'f771b328ab06'
是錯誤中的用戶標識。我可以添加一個新用戶並阻止用戶被複制,但是當我嘗試將他們的位置添加到列表中時,出現此錯誤。
有人看到有什麼問題嗎?該錯誤發生在初始化函數的else
語句中(如果用戶標識存在,只需追加位置並且不創建新用戶)。我在代碼中有一些註釋,我敢肯定,這部分是由於我修改了另一個用戶提供的示例。
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:");
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
因爲我從電話的ID,並且不需要在這裏生成它(只接受它),我註釋掉創建隨機ID的一部分。在這樣做的時候,我不得不在Users()
內爲createUser
方法添加一個參數,這樣我就可以將這個ID作爲參數從Initialize()
傳遞過來。看到的變化到createUser
下面:
之前,與所生成的ID(在其中產生數量與註釋上面的代碼塊中的部分):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
後,與作爲通過ID參數:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
如果有人有任何建議,我會非常感激。謝謝!
好,我是新來的JS,我只是想能夠搜索,以防止標識被複制的鑰匙。我把「1」作爲佔位符。有沒有更好的方法來做到這一點? – mkyong 2012-01-31 13:15:41
我明白了。我沒有在if語句中定義用戶。哎呀。我註釋掉了'users.users [user_id] =「1」;'部分,它似乎工作正常。感謝您的洞察力。 – mkyong 2012-01-31 13:31:20
如果你是新的結賬Firebug,它可能真的幫助你調試你的代碼。 – AsTeR 2012-01-31 13:45:08