Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access prototype function from this

Tags:

javascript

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?

like image 489
Mike S Avatar asked Sep 18 '26 01:09

Mike S


2 Answers

Three things:

  • use new Container(); instead of Container();.
  • Move this new Container(); line AFTER all prototype additions.
  • Call 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.

like image 121
Tahir Ahmed Avatar answered Sep 19 '26 15:09

Tahir Ahmed


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.

like image 21
TGH Avatar answered Sep 19 '26 16:09

TGH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!