如果我有:
function Person(name, age){
this.name = name;
this.whoIs = function(){
alert('I am ' + this.name);
}
}
var john = new Person('John');
john.whoIs();
一切都会正常,我会收到一个很好的提醒:“我是约翰”。
有没有办法在构造函数之后向原型(prototype)添加方法,并且可以访问构造函数参数?
类似于:
function Person(name, age){
this.name = name;
this.whoIs = function(){
alert('I am ' + this.name);
}
}
Person.prototype.age = Person.arguments[1];
var john = new Person('John', 20);
john.age; // would give 20
有办法做到这一点吗?即:能够向原型(prototype)添加属性或方法,以便在创建新实例时可以访问参数?
最佳答案
在原型(prototype)中拥有动态属性是没有意义的。将原型(prototype)视为对象的蓝图。
您可以这样做:
function Person(name, age){
this.name = name;
this.whoIs = function(){
alert('I am ' + this.name);
}
this.age = age;
}
var john = new Person('John', 20);
john.age; // would give 20
<小时/>
此外,还为每个 Person
对象添加了 whoIs
函数。您可以将其添加到原型(prototype)中:
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.whoIs = function () {
return 'I am ' + this.name;
}
var john = new Person('John', 20);
john.whoIs(); // would give "I am John"
关于javascript - 使用构造函数参数向 Prototype 添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27594421/