2013-10-21 95 views
0

是否可以重寫JavaScript中的函數?在蟒蛇比如我可以在一個文件中做到這一點:在JavaScript中重寫函數

#file one.py 
class Test: 
    def say(self,word): 
     pass 
    def speak(self): 
     self.say("hello") 

然後在另一個文件中做到這一點:

import one 
class Override(one.Test): 
    def say(self,word): 
     print(word) 
if __name__ == "__main__": 
    Override().speak() 

這可以將其打印(「你好」),而不是傳遞,因爲覆蓋的。

是否存在與JavaScript等效的內容?

+0

你能不能寫一個JavaScript的例子嗎? – Blender

+1

你的意思是繼承? Javascript的繼承是奇怪的(它是原型而不是古典),但是如果你在Javascript中查找繼承,你應該找到如何做到這一點。 –

回答

5
function Test() {} 

Test.prototype.say = function (word) { 
    alert(word); 
} 

Test.prototype.speak = function() { 
    this.say('hello'); 
} 

Test.prototype.say = function (word) { 
    console.log(word); 
} 

最後分配將覆蓋所有測試對象的發言權方法。如果你想覆蓋它在繼承函數(類):

function Test() {} 

Test.prototype.say = function (word) { 
    alert(word); 
} 

Test.prototype.speak = function() { 
    this.say('hello'); 
} 

function TestDerived() {} 

TestDerived.prototype = new Test(); // javascript's simplest form of inheritance. 

TestDerived.prototype.say = function (word) { 
    console.log(word); 
} 

,如果你想覆蓋它在測試的特定實例:

function Test() {} 

Test.prototype.say = function (word) { 
    alert(word); 
} 

Test.prototype.speak = function() { 
    this.say('hello'); 
} 

var myTest = new Test(); 

myTest.say = function (word) { 
    console.log(word); 
}