New object using values by default

Discussion in 'Javascript' started by Archos, Feb 17, 2012.

  1. Archos

    Archos Guest

    function Base(x, y) { this._zero=0,0; this.x=x; this.y=y; }

    I want to create an object of two ways:

    + Passing values

    var b = new Base(2, 3)

    (This way works)

    + Using the values that are in '_zero'. For that example, 0 should be
    passed to 'x', and another 0 to 'y'.
     
    Archos, Feb 17, 2012
    #1
    1. Advertisements

  2. Archos

    Archos Guest

    On Feb 18, 3:34 am, RobG <> wrote:
    > On 17/02/12 7:04 PM, Archos wrote:
    >
    > > function Base(x, y) { this._zero=0,0; this.x=x; this.y=y; }

    >
    > > I want to create an object of two ways:

    >
    > > + Passing values

    >
    > > var b = new Base(2, 3)

    >
    > > (This way works)

    >
    > > + Using the values that are in '_zero'. For that example, 0 should be
    > > passed to 'x', and another 0 to 'y'.

    >
    > You might try:
    >
    >    function Base(x, y) {
    >      this.default = {x:0, y:0};
    >      this.x = typeof x == undefined? this.default.x : x;
    >      this.y = typeof y == undefined? this.default.y : y;
    >    }
    >
    > Or some other suitable test for the values passed to x and y. You could
    > also use a getter:
    >
    >    Base.prototype.getX = function() {
    >      return this.x == undefined? this.default.x : this.x;
    >    }
    >
    > and so on.

    And to do it more generic:

    function T(_z) { this._z={};
    this._z=_z;
    }

    T.prototype.zero = function() {
    var m = {};

    for (k in this._z) {
    m.k = this._z[k];
    }
    return m;
    }

    ==

    T.prototype.Point = function(x, y) {
    this._z={x:0,y:0}; this.x=x; this.y=y;
    }
    T.prototype.Sum = function(a, b) {
    this._z={a:0,b:0}; this.a=a; this.b=b;
    }

    var p = new Point(12, 10);
    var p2 = new Point().zero();
     
    Archos, Feb 18, 2012
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.