是否可以重新定义JavaScript类的方法? [英] Is it possible to redefine a JavaScript class's method?
问题描述
在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
方法将被调用:
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
编辑:
我意识到我可以发送一个参数像Hello或Hola到 sayHello
完成不同的输出。我也意识到我可以简单地分配一个新的函数给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屋!