使用 contructor 参数将新属性添加到原型

Add new property to Prototype using contructor argument

本文关键字:属性 添加 原型 contructor 参数 新属性 使用      更新时间:2023-09-26

如果我有:

function Person(name, age){
   this.name = name;
   this.whoIs = function(){
        alert('I am ' + this.name);
   }
}
var john = new Person('John');
john.whoIs();

一切都会好起来的,我会得到一个很好的提醒:"我是约翰"。

有没有办法在构造函数之后将方法添加到原型中,并且可以访问构造函数参数?

像这样:

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

有没有办法做到这一点?即:能够将属性或方法添加到创建新实例时可以访问参数的原型?

在原型中具有动态属性是没有意义的。将原型视为对象的蓝图。

您可以这样做:

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 函数。您可以改为将其添加到原型中:

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"