Wednesday, 19 July 2017

How to access class variables from inner prototype - javascript

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.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...