0

是否可以覆盖 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()

由于覆盖,这可能会打印(“hello”)而不是通过。

有 JavaScript 等价物吗?

4

1 回答 1

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

如果您想在特定的测试实例中覆盖它:

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);
}
于 2013-10-21T03:25:16.040 回答