且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以重新定义 JavaScript 类的方法?

更新时间:2023-09-11 21:31:52

以后可以重新定义类的方法吗?

is it possible to redefine the class's method later?

是的.但是,您不能将新函数分配给 Person 构造函数的属性,而是分配给实例本身:

Yes. However, you must not assign the new function to a property of the Person constructor, but to the instance itself:

var p2 = new Person("Sue");
p2.sayHello();   // Hello, Sue
p2.sayHello = function() {
   alert('Hola, ' + this.name);
};
p2.sayHello();   // Hola, Sue

如果您想自动为所有新实例执行此操作(并且没有使用该方法的原型,您可以像@dystroy 的回答一样轻松地进行交换),您将需要 装饰构造函数:

If you want to do this for all new instances automatically (and have not used the prototype for the method, which you easily could exchange as in @dystroy's answer), you will need to decorate the constructor:

Person = (function (original) {
    function Person() {
        original.apply(this, arguments);   // apply constructor
        this.sayHello = function() {       // overwrite method
            alert('Hola, ' + this.name);
        };
    }
    Person.prototype = original.prototype; // reset prototype
    Person.prototype.constructor = Person; // fix constructor property
    return Person;
})(Person);