javascript - 使用构造函数参数向 Prototype 添加新属性

标签 javascript prototype

如果我有:

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/

相关文章:

javascript - 为什么间接更改复选框时不会触发复选框上的 onchange

javascript - 对 JavaScript 原型(prototype)继承感到困惑

javascript - 为什么 MatterJS 物理坐标与 DOM 元素有偏移?

javascript - 如何插入像 forEach、reduce 之类的参数?

c - 是什么导致编译器警告未使用的函数?

javascript - 从 sql footable 重新加载数据

javascript原型(prototype)继承混淆

javascript - backbone.js 路由器中的严格参数匹配

javascript - 是否可以在 DIV 单击时调出设备的数字键盘?

javascript - JQuery Mobile + ChartJS : Responsive Bar Chart displayed only after resizing