I am trying to fix some Javascript that uses functions and prototype functions. For some reason the prototype function is always undefined when I try to access it and I can't figure out why.
Here is a simple example of what I'm trying to do. Basically, I want to reference the _open prototype from within the original Container function declaration using this.
Container();
function Container() {
alert(this._open);
}
Container.prototype._open = function() {
alert("hey");
}
You can see in fiddle that it just alerts "undefined." But this question and this question both show examples of people doing this. Why do I keep getting undefined?
Three things:
new Container(); instead of Container();.new Container(); line AFTER all prototype additions.this._open(); instead of alert(this._open); to actually execute
the function.So your code should look like this:
function Container() {
this._open();
}
Container.prototype._open = function() {
alert('open');
}
new Container();
Hope this helps.
function Container() {
this._open();
}
Container.prototype._open = function() {
alert("hey");
}
var container = new Container();
Try the above. You need to create an instance of the object using new.
Otherwise this refers to the global object and not the prototype members.
Using constructors without new() causes weird bugs. Since this will refer to the global objected === window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With