覆盖Javascript中的函数

rul*_*ler 0 javascript python

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

#file one.py
class Test:
    def say(self,word):
        pass
    def speak(self):
        self.say("hello")
Run Code Online (Sandbox Code Playgroud)

然后在另一个文件中这样做:

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

这可能会打印("你好")而不是因为覆盖而传递.

是否有JavaScript等价物?

Nic*_*aub 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);
}
Run Code Online (Sandbox Code Playgroud)

最后一个赋值将覆盖所有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);
}
Run Code Online (Sandbox Code Playgroud)

如果要在特定的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);
}
Run Code Online (Sandbox Code Playgroud)