When using a constructor function in JavaScript to create a class, is it possible to redefine the class's method later?
Example:
function Person(name)
{
this.name = name;
this.sayHello = function() {
alert('Hello, ' + this.name);
};
};
var p = new Person("Bob");
p.sayHello(); // Hello, Bob
Now I'd like to redefine sayHello
like this:
// This doesn't work (creates a static method)
Person.sayHello() = function() {
alert('Hola, ' + this.name);
};
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
EDIT:
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); };
I'm just wondering if I can redefine the class's method so new instances of Person
will use the new sayHello
method.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…