1

I might not be clear with my title of the question. Sorry for that.

Here is what I wanted to do.

I'm trying to use prototyping pattern in javascript. I created a class as following.

var MyClass = null;
(function() {
    MyClass = function() {
        this.clsVar = "I'm inside constructor";
    };

    MyClass.prototype = {
        constructor: MyClass,
        myFunc1: function() {
            console.log("I'm func1 accessing constructor variable : " + this.clsVar);
        },
        nested: {
            myFunc2: function() {
                console.log("I'm func2 accessing constructor variable : " + this.clsVar); // I know, this will never point to the class scope
            }
        }
    }
}())

I'm creating an object.

var my = new MyClass();

my.myFunc1(); // which prints "I'm func1 accessing constructor variable : I'm inside constructor" 

my.nested.myFunc1(); // as expected, it prints "I'm func2 accessing constructor variable : undefined

All I am trying to do is, I should be able to access clsVar from nested.myFunc2

is that possible.? Any help is greatly appreciated and needed. Thanks.

Malleswari
  • 331
  • 1
  • 13

2 Answers2

1

Actually, there is a point.

The this inside your myFunc2 does not refer anymore to MyClass but to another context. So, the fastest way is to do is to use call or apply like:

var myNewObject = new MyClass();
myNewObject.nested.myFunc2.call(myNewObject, arg1, arg2);

or

myNewObject.nested.myFunc2.apply(myNewObject, [arg1, arg2]);
steo
  • 4,586
  • 2
  • 33
  • 64
0

JavaScript's prototype-based class system does not allow this. MyClass's prototype will be shared between all instances of the class. In the following code, both instances will use the same function instance...

var first = new MyClass(), second = new MyClass();
first.nested.myFunc2(); <-- Same prototype function
seecond.nested.myFunc2(); <-- Same prototype function

When the code enters the "myFunc2" definition, which parent should it be accessing?

If you need access to the parent's "this" value, you'll have to use a closure and set up the nested object in the parent constructor as below.

var MyClass = null;

(function() {
    MyClass = function() {
        this.clsVar = "I'm inside constructor";
        var that = this;
        this.nested = {
            myFunc2: function() {
                console.log("I'm func2 accessing constructor variable : " + that.clsVar); // I know, this will never point to the class scope
            }
         }
    };

    MyClass.prototype = {
        constructor: MyClass,
        myFunc1: function() {
            console.log("I'm func1 accessing constructor variable : " + this.clsVar);
        }
    }
}())
James Thomas
  • 4,303
  • 1
  • 20
  • 26