覆盖Javascript中的函数

时间:2013-10-21 03:22:14

标签: javascript python

是否可以覆盖JavaScript中的函数?例如,在python中,我可以在一个文件中执行此操作:

#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等价物?

1 个答案:

答案 0 :(得分: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);
}

最后一个赋值将覆盖所有Test对象的say方法。如果要在继承函数(类)中覆盖它:

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

如果要在特定的test实例中覆盖它:

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