2013-10-06 48 views
1

这是我的JavaScript代码:功能扩展其他功能与原型

function animal(){ 
    var animal_sound; 
    this.animal = function(sound){ 
     animal_sound = sound; 
    } 

    this.returnSound = function(){ 
     return animal_sound; 
    } 
} 

function cat(){ 
    this.cat = function(sound){ 
     this.animal(sound); 
    } 
} 
cat.prototype = new animal() 
cat.prototype.constructor = cat; 

//Create the first cat 
var cat1 = new cat(); 
cat1.cat('MIAO');//the sound of the first cat 

//Create the second cat 
var cat2 = new cat(); 
cat2.cat('MIAAAAUUUUUU');//the sound of the second cat 

alert(cat1.returnSound()+' '+cat2.returnSound()); 

只要我有cat功能扩展animal功能。比我创造了两只不同的猫(cat1cat2)。每只猫都有自己的声音,但是当我打印他们的声音,我获得:

MIAAAAUUUUUU MIAAAAUUUUUU

cat2声音覆盖cat1声音,我也不想这样。

我想获得:

MIAO MIAAAAUUUUUU

谁能帮助我?

回答

0

animal().returnSound()方法在原型上,所以它们在cat的所有实例之间共享。

因为他们在animal构造函数创建,并利用每次调用.animal()时间在构造函数中的作用域的变量,你覆盖所使用的.animal().returnSound()相同的变量。

要做你想做的事,你需要为每个cat创建一个新的.animal().returnSound()方法。


function animal(){ 
    var animal_sound; 
    this.animal = function(sound){ 
     animal_sound = sound; 
    } 

    this.returnSound = function(){ 
     return animal_sound; 
    } 
} 

function cat(){ 
    animal.call(this); // apply the `animal()` function to the new `cat` object 
    this.cat = function(sound){ 
     this.animal(sound); 
    } 
} 
cat.prototype = new animal() 
cat.prototype.constructor = cat; 

现在,当您创建的猫,他们将有自己的.animal().returnSound()方法,这将在animal单独调用每个cat创建,这样就会有一个新的animal_sound每对这些方法。

var cat1 = new cat(); 
cat1.cat('MIAO'); 

var cat2 = new cat(); 
cat2.cat('MIAAAAUUUUUU'); 

alert(cat1.returnSound()+' '+cat2.returnSound()); // MIAO MIAAAAUUUUUU 

当然,在这样做,你不采取原型继承的多少优势。

+0

非常感谢您的时间:)现在,它的工作原理! – Fabio

0

那是因为你设置的雏形了

cat.prototype = new animal() 

每个动物实例都有自己的“私人” animal_sound变量,但所有cat实例从相同animal实例继承,因此他们“分享”这个变量。

相反,你应该调用animal每个cat实例:

function cat(){ 
    animal.call(this); 

    this.cat = function(sound){ 
     this.animal(sound); 
    } 
} 

你甚至都不需要在这种情况下,任何分配给cat.prototype。但是,如果您打算将方法添加到原型(您应该),请使用Object.create来设置继承。更多的信息在这里:Benefits of using `Object.create` for inheritance

+0

非常感谢您的先生!我感谢您的帮助! – Fabio