Tuesday, November 12, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...