在JavaScript中覆盖函数

use*_*697 33 javascript prototype

可能重复:
使用JavaScript原型调用基本方法

我想继承将覆盖javascript函数的继承对象.

从我想要调用基本方法的方法.在这种情况下,我继承对象readerPerson现在我要重写的功能,getName这意味着在读者首先我要上调用的函数Person,然后做一些改变.

<script>
    /* Class Person. */
    function Person(name) {
        this.name = name;
    }
    Person.prototype.getName = function() {
        return this.name;
    }

    var reader = new Person('John Smith');
    reader.getName = function() {
        // call to base function of Person, is it possible?
        return('Hello reader');
    }
    alert(reader.getName());
</script>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ogt 32

Vincent回答了你的直接问题,但是如果你想建立一个真正的继承层次结构,你可以做什么,你可以进一步扩展Reader.

创建你的人员课程:

function Person(name) {
    this.name = name;
}

Person.prototype.getName = function(){
    alert('Person getName called for ' + this.name);
    return this.name;
}
Run Code Online (Sandbox Code Playgroud)

创建一个Reader类:

function Reader(name) {
    // Calls the person constructor with `this` as its context
    Person.call(this, name);
}

// Make our prototype from Person.prototype so we inherit Person's methods
Reader.prototype = Object.create(Person.prototype);

// Override Persons's getName
Reader.prototype.getName = function() {
    alert('READER getName called for ' + this.name);
    // Call the original version of getName that we overrode.
    Person.prototype.getName.call(this);
    return 'Something';
}
Reader.prototype.constructor = Reader;
Run Code Online (Sandbox Code Playgroud)

现在我们可以重复一个类似的过程,用一个VoraciousReader来扩展Reader:

function VoraciousReader(name) {
    // Call the Reader constructor which will then call the Person constructor
    Reader.call(this, name);
}

// Inherit Reader's methods (which will also inherit Person's methods)
VoraciousReader.prototype = Object.create(Reader.prototype);
VoraciousReader.prototype.constructor = VoraciousReader;
 // define our own methods for VoraciousReader
//VoraciousReader.prototype.someMethod = ... etc.
Run Code Online (Sandbox Code Playgroud)

小提琴:http: //jsfiddle.net/7BJNA/1/

Object.create:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create

Object.create(arg) 正在创建一个新对象,其原型是作为参数传递的.

编辑 自这个原始答案以来已经存在多年,现在Javascript支持class关键字,如果您来自Java或C++等语言,它可以正常运行.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes


Vin*_*ert 28

由于您正确地覆盖了对象本身的函数而不是其原型,您仍然可以使用对象调用原型函数.

reader.getName = function() {
    var baseName = Person.prototype.getName.call(this);
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 为了更加动态,使用`Object.getPrototypeOf(this).getName.call(this);`如果ES5可用. (4认同)
  • 我将使用Person.prototype.getName.apply(this,arguments),以便您不会丢失任何参数。除非您特别不想传递参数。 (2认同)

Abs*_*lom 5

我使用 John Resig 的这项技术来获得继承和方法覆盖。它甚至可以让您通过调用 this._super() 来访问被覆盖的方法。

http://ejohn.org/blog/simple-javascript-inheritance/