SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Aug 2008
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript Object Constructor - Initialization

    I have created a simple javascript class and have a question regarding object construction/initialization.

    Can I have a method run upon initialization?

    ex:

    // Somewhere in main script
    // Object initialization
    var elem = new InputElement(inputId, inputVal);


    // Object constructor
    function InputElement(id, val) {
    this.id = id;
    this.val = val;

    // Can I do this?
    init(this.id, this.val);
    }

    Can I have an initialization method called upon object construction?

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2009
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi,

    an example:

    Code JavaScript:
    function InputElement(id, val) {
    	this.init (id, val);
    }
     
    InputElement.prototype.init = function (id, val) {
    	this.id = id;
    	this.val = val;
    }
     
    InputElement.prototype.getID = function () {
    	return this.id;
    }
     
    InputElement.prototype.getVal = function () {
    	return this.val;
    }
     
    var elem = new InputElement ("myInput", "myValue");
     
    alert (elem.getID ());
    alert (elem.getVal ());
    Gumape

  3. #3
    SitePoint Member
    Join Date
    Aug 2008
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •