是否可以重新定义 JavaScript 类的方法? [英] Is it possible to redefine a JavaScript class's method?

查看:27
本文介绍了是否可以重新定义 JavaScript 类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中使用构造函数创建类时,是否可以稍后重新定义类的方法?

When using a constructor function in JavaScript to create a class, is it possible to redefine the class's method later?

示例:

function Person(name)
{
    this.name = name;
    this.sayHello = function() {
        alert('Hello, ' + this.name);
    };
};

var p = new Person("Bob");
p.sayHello();   // Hello, Bob

现在我想像这样重新定义sayHello:

Now I'd like to redefine sayHello like this:

// This doesn't work (creates a static method)
Person.sayHello() = function() {
   alert('Hola, ' + this.name);
};

所以当我创建另一个 Person 时,新的 sayHello 方法将被调用:

so when I create another Person, the new sayHello method will be called:

var p2 = new Person("Sue");
p2.sayHello();   // Hola, Sue
p.sayHello();    // Hello, Bob

我意识到我可以向 sayHello 发送诸如Hello"或Hola"之类的参数来完成不同的输出.我也意识到我可以像这样简单地为 p2 分配一个新函数:

I realize I could send in an argument like "Hello" or "Hola" to sayHello to accomplish the different output. I also realize I could simply assign a new function to p2 like this:

p2.sayHello = function() { alert('Hola, ' + this.name); };

我只是想知道是否可以重新定义类的方法,以便 Person 的新实例将使用新的 sayHello 方法.

I'm just wondering if I can redefine the class's method so new instances of Person will use the new sayHello method.

推荐答案

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

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

这篇关于是否可以重新定义 JavaScript 类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆