0

I'm trying to create a function constructor:

var obj = function() {
    this.num = 2;
    this.func = function() {
        // need to access the **instance** num variable here
    };
};

var instance = new obj();

I need to access the instance properties from a propery (which is the function func) of the object. But it doesn't work, since this is always the current function..

1
  • Even your code works fine. Commented Mar 9, 2015 at 11:50

4 Answers 4

3

Store this in a variable which func can access:

var obj = function() {
    var _this = this;
    _this.num = 2;
    _this.func = function() {
        console.log(_this.num);
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

It's interesting that you do _this.num and _this.func too. Is that something you for consistency in your code? Because I'd just leave them as this and only use _this in the method.
@Andy That's right it's purely for consistency / maintainability. There is no performance improvement either way
0

Please, use well-known approach, store this into separate field:

    var obj = function() {
      self = this;
      self.num = 2;
      self.func = function() {
       alert(self.num);
          // need to access the **instance** num variable here
      };
    };

   var instance = new obj();

Comments

0

This is the pattern I use for the problem:

var obj = function(){
  var self = this;
  this.num = 2;
  this.func = function() {
    console.info(self.num);
  };
};

var instance = new obj();

The variable self now can be accessed in all function of obj and is always the obj itself.

This is the same then:

var obj = function(){
  var self = this;
  self.num = 2;
  self.func = function() {
    console.info(self.num);
  };
};

var instance = new obj();

1 Comment

I see self is a local variable. And I guess it wont be garbage collected? Does self simply created again for each scope, and it's similar to static variable in C ?
0

You can do it using the Custom Constructor Functions, used to create a custom constructor and it's accessed without any problem, try it:

var Obj = function () {
     this.num = 2;
     this.func = function () {
         alert("I have " + this.num);
         return "I have " + this.num;
     };
};

var instance= new Obj();
instance.func();//will return and show I have 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.