Rikard
Rikard

Reputation: 7805

Add new property to Prototype using contructor argument

If I have:

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

all will work and I will get a nice alert with: "I am John".

Is there a way to add method to the prototype after the constructor and that will have access to the constructor arguments?

Something like:

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

Is there a way to do this? Ie: being able to add a property or method to a prototype that will have access to the arguments when a new instance is created?

Upvotes: 0

Views: 34

Answers (1)

Halcyon
Halcyon

Reputation: 57719

It doesn't make sense to have a dynamic property in the prototype. See the prototype as the blueprint of your object.

You can do this:

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

Also, the whoIs function is added for each Person object. You can add it to the prototype instead:

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"

Upvotes: 3

Related Questions