[英]Javascript prototype override
我有這段代碼,可以讓我返回有關連接到特定帖子的帖子的字符串。 我在訪問列表部分下面的屬性時嘗試使用方括號和點表示法( list=list+this["connectionsTo"[i]].postNum+"\\n";
),但不起作用。 但是當我使用雙點符號時,為什么呢? 我相信那兩個是一樣的。
function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
}
Fencepost.prototype = {
sendRopeTo: function(connectedPost) {
this.connectionsTo.push(connectedPost);
},
removeRope: function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
},
movePost: function(x, y) {
this.x = x;
this.y = y;
},
valueOf: function() {
return Math.sqrt(this.x * this.x +
this.y * this.y);
}
};
Fencepost.prototype.toString=function(){
var list="";
for(var i=0;i<this.connectionsTo.length;i++){
list=list+this["connectionsTo"[i]].postNum+"\n";
}
return "Fence post #"+this.postNum+":\nConnected to posts:\n"+list+"Distance from ranch: "+this.valueOf()+" yards";
};
var post10=new Fencepost(3,4,10);
var post11=new Fencepost(5,7,11);
var post12=new Fencepost(6,7,12);
var post13=new Fencepost(8,9,13);
post10.sendRopeTo(post11);
post10.sendRopeTo(post12);
post10.sendRopeTo(post13);
console.log(post10.toString());
由於您要遍歷this.connectionsTo
數組,因此您正在尋找
this["connectionsTo"][i]
或同等學歷
this.connectionsTo[i]
代替
this["connectionsTo"[i]]
索引字符串,然后將該字符用作this
的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.