phunder
phunder

Reputation: 1713

First try at JavaScript Prototyping

I am just getting my feet wet where JavaScript Prototyping is involved, and I am having some trouble.

I need to create a _LEAVE object from a LEAVE prototype for a system I am working on based on a prototype object. The _LEAVE object has a function named Ready, which should fire when the document is ready. The system already has similar functionality in some of it's older code, and I am trying to keep it uniform.

Here is the code I am trying, but I keep getting an error:

var LEAVE = function () {

}

$(document).ready(function () {
    _LEAVE.Ready();
});


var _LEAVE = function (params) {

    this.Ready = function () {
        alert ("Leave Ready");
    };
}

_LEAVE.prototype = new LEAVE();

Error:

SCRIPT438: Object doesn't support property or method 'Ready' leave.js, line 6 character 5

I'm not sure where I am going wrong, as this seems to be what is happening in other parts of the system. At least, something similar is happening, but I am struggling to wrap my mind around the old code...

Would appreciate any advice anyone could give me! :-)

Upvotes: 0

Views: 82

Answers (2)

codeVerine
codeVerine

Reputation: 762

What you have done here is just inherited the child _LEAVE function from parent LEAVE function. But if you want to call a method in the child class, you need to create an instance of it. So you need to create an instance of the _LEAVE class. just add this line :

var _LEAVE_OBJECT = new _LEAVE();

and use _LEAVE_OBJECT.Ready() instead of _LEAVE.Ready(); in $(document).ready.

Modified code :

var LEAVE = function () {

}

$(document).ready(function () {
 _LEAVE_OBJECT.Ready();
});


var _LEAVE = function (params) {
   this.Ready = function () {
    alert ("Leave Ready");
    };  
}
_LEAVE.prototype = new LEAVE();
var _LEAVE_OBJECT = new _LEAVE();

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

I'm not sure if I've understood you correctly, but are you attempting to create an instance of a LEAVE object? If so, LEAVE needs to be a constructor function, and Ready should be a method on the prototype of that:

var LEAVE = function () {};
LEAVE.prototype.Ready = function () {
    alert("Leave Ready");
};

Now, you can instantiate LEAVE by calling the constructor with the new operator:

var _LEAVE = new LEAVE(); // _LEAVE is an instance of LEAVE
$(document).ready(function () {
    _LEAVE.Ready(); // Ready is a method of `LEAVE.prototype`
});

Methods declared as properties of the prototype object are shared by all instances. So all instances of LEAVE will have a .Ready method available to them, but they will share one copy of the function in memory (the copy that was assigned to the property of LEAVE.prototype).

Upvotes: 3

Related Questions