Sunday, February 24, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...