简体   繁体   English

Javascript原型覆盖

[英]Javascript prototype override

I have this code that allows me to return a string about the posts connected to a particular post. 我有这段代码,可以让我返回有关连接到特定帖子的帖子的字符串。 I tried to use the bracket and dot notation in accessing properties below in the list part ( list=list+this["connectionsTo"[i]].postNum+"\\n"; ) but doesn't work. 我在访问列表部分下面的属性时尝试使用方括号和点表示法( list=list+this["connectionsTo"[i]].postNum+"\\n"; ),但不起作用。 But then when I used the double dot notation, it worked, why? 但是当我使用双点符号时,为什么呢? I believe those two are the same. 我相信那两个是一样的。

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());

Since you are iterating over the this.connectionsTo array, you are looking for 由于您要遍历this.connectionsTo数组,因此您正在寻找

this["connectionsTo"][i]

or the equivalent 同等学历

this.connectionsTo[i]

instead of 代替

this["connectionsTo"[i]]

which indexes the string, and then takes that character for the property of this . 索引字符串,然后将该字符用作this的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM