0

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

Avishay
  • 305
  • 1
  • 11
  • 1
    wht you mean by send this class constructor values ? – Sarath Apr 08 '14 at 08:13
  • 3
    Both your question and your example are incomprehensible. You're talking about creating an _object_ and demonstrate it by creating a _constructor_; then you use an undefined variable in said constructor, while disregarding its argument; then you talk about "sending values to this constructor", which means nothing. Consider editing your question and describing your issue more clearly. – lanzz Apr 08 '14 at 08:13
  • You would need [proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy "Proxy - JavaScript | MDN"). Unfortunately they are not implemented in JavaScript yet. What's your use case? I am sure that there must be easier ways to solve your problem. – Aadit M Shah Apr 08 '14 at 08:17
  • You're going to receive the following: `ReferenceError: living is not defined`. – rxgx Apr 08 '14 at 17:55

2 Answers2

0

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})
Łukasz Szewczak
  • 1,851
  • 1
  • 13
  • 14
0

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375