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

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.
Similar Threads
  1. winderjj
    Replies:
    1
    Views:
    553
    Richard Tobin
    Jul 31, 2003
  2. aurgathor
    Replies:
    4
    Views:
    670
    aurgathor
    Mar 19, 2005
  3. C Gillespie
    Replies:
    3
    Views:
    642
    Peter Hansen
    Mar 22, 2005
  4. Ron Adam
    Replies:
    3
    Views:
    512
    Ron Adam
    Oct 14, 2005
  5. Daniel Pitts
    Replies:
    7
    Views:
    822
  6. Replies:
    4
    Views:
    433
    Thomas 'PointedEars' Lahn
    Dec 23, 2007
  7. John Nagle
    Replies:
    3
    Views:
    264
    Thomas 'PointedEars' Lahn
    Feb 25, 2008
  8. Replies:
    2
    Views:
    875
    Thomas 'PointedEars' Lahn
    Mar 11, 2008
Loading...