Domanda

Edited: Say i create a constructor to create my own user-defined objects:

var Person = Person(age) { this._age = living; };

and i find during runtime that i need to add to the objects that are created by this constructor another property,so i use this to add the property the prototype.

Person.prototype.alive;

now my only constructor gets only 1 val, is it possible to send that same constructor another val? say something like var newPerson = Person(20,''yes);

È stato utile?

Soluzione

is it possible to send that same constructor another val? say something like var newPerson = Person(20,'yes');

No. The constructor you have does only take one parameter.

You can however redefine the constructor, in your case:

Person = (function (original) {
    function Person(age, alive) {
        original.call(this, age);          // apply constructor
        this.alive = alive;                // set new property from new parameter
    }
    Person.prototype = original.prototype; // reset prototype
    Person.prototype.constructor = Person; // fix constructor property
    return Person;
})(Person);

Notice that the old object created before this will automagically get assigned new values. You'd need to set them like oldPerson.alive = 'no'; explicitly for every old instance that you know.

Altri suggerimenti

If You consider passing different parameters to constructor, it would be friendlier write constructor to accept single object specifier

function Person({paramZ: val, paramX: val})
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top