javascript - 使用全局变量交叉原型

时间:2015-05-11 05:07:03

标签: javascript

我有这个对象:

var Song = function(side, name, index, duration, author, lyrics) {
    this.side = side;
    this.name = name;
    this.index = index;
    this.duration = duration;
    this.author = author;
    this.lyrics = lyrics;
    globalLyrics.push(this.lyrics);
 };

使用例如:

    var song1 = new Song('Mithras', 'Wicked', 1, '3:45', 'Me and The Plant', 
           ["politicians", "politician", "politics", "telling", 
           "lies", "lie", "to", "media", "the", "youngsters", 
           "young", "elders", "time", "that", "passes", "pass", "by", 
           "oh", "no", "lie", "detector", "detection", "souls", "as", 
           "far", "illusion", "goes", "all", "sinners", "sin", "around", 
           "sun", "earth", "atom", "atoms", "mind", "angels", "angel", 
           "prophet", "prophets", "martyr", "knives", "elder", "detect", 
           "shit", "flies", "fly", "meat", "is", "knife", "and", "death", 
           "life", "I", "am", "gonna", "going", "cast", "a", "sacred", 
           "circle"]);

给定一个全局变量的输入:

    var input = ["politician", "going", "cast"];

和countIntersection函数:

   function countIntersect(input, lyrics) {

       var temp = [];
       for(var i = 0; i < input.length; i++){
           for(var k = 0; k < lyrics.length; k++){
              if(input[i] == lyrics[k]){
                  temp.push(input[i]);
                  break;
               }
           }
        }
        return temp.length;   
     }

问题:

我不想让input成为歌曲prototype的一部分。

如何调整此countIntersection function,以便global inputthis.lyrics相交?

1 个答案:

答案 0 :(得分:0)

您需要在countIntersection对象上设置Song方法,或将Song实例传递给该功能(而不仅仅是歌词)。

例如:

var Song = function () {...}
Song.prototype.countIntersect = function (input) {
   var lyrics = this.lyrics;
   var count = 0;

   for(var i = 0; i < input.length; i++) {
       for(var k = 0; k < lyrics.length; k++){
          if(input[i] == lyrics[k]){
              count += 1;
           }
       }
    }

    return count;  
 }

然后

var song1 = new Song(...);

song1.countIntersect(input); // 21