且构网

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

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

更新时间:2023-09-11 21:27:34


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

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