Elad Katz
Elad Katz

Reputation: 7591

how to get a reference to the defining 'class' inside an inner method in JavaScript?

I have the following JS code:

var Item = function ()
{
    this.property = '';
    this.myfunction = function ()
    {
        var value = this.property;
    };

};

however, this does not point to the defining class so value doesn't get anything.

how do I access this.property from inside my function?

Upvotes: 0

Views: 79

Answers (4)

Mrchief
Mrchief

Reputation: 76198

You need to create a closure which captures the value of parent scope's this:

var Item = function ()
{
    this.property = '';
    var self = this;
    this.myfunction = function ()
    {
        var value = self.property;
    };

};

Update: As others have pointed out, this closure is not needed when Item is used as a constructor (new Item()). Noting it here for future reference.

Upvotes: 3

chjj
chjj

Reputation: 14602

this changes depending on the context. The context being how a function was invoked, not how it was defined, but how it was called.

Besides that, you seem to be mixing up two patterns here. I'm sure you meant something like:

var Item = function() {
  this.property = '';
};

Item.prototype.myfunction = function() {
  var value = this.property;
};

Instead you kind of mixed a closure pattern with prototypal, which doesn't seem very useful there. Closure is good for hiding members, allowing for true private members, but here you're exposing the property anyway. There's no reason not to stick that function on the prototype.

Do yourself a favor and ignore any concepts you have of more traditional OO, they won't do you any good here. Prototypal isn't nearly the same thing.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

Your code works as is if you call Item() as a constructor.

var item = new Item();
item.property = "the property";
item.myfunction(); // value = "the property"

Upvotes: 1

lhchavez
lhchavez

Reputation: 43

just create an alias for this. It will get closure'd.

var Item = function ()
{
    this.property = '';
    var self = this;
    this.myfunction = function ()
    {
        var value = self.property;
    };

};

Upvotes: 2

Related Questions