質問

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);

役に立ちましたか?

解決

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.

他のヒント

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})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top