0

I am expanding my JS knowledge by building custom libraries on-top of jQuery/JS and the classes have to interact between each other. I am coming from PHP, so there I could use static variables, but have no idea in JS. Here is an example of what I want:

var A = function() {
    this.myPublicVar = "thisShouldBePrintedFromClassB";
}

A.prototype = {
    showMyVar : function() {alert(this.myPublicVar);} // This gets triggered on direct access.
}

var B = function() {}
B.prototype = {
    // I have no idea how to to access A.myPublicVar
}

Anyone could provide me with simple tutorial or anything?

PS: I have just started to expand my JS knowledge, have used JS/jQuery for easy design purposes (using selectors and building data validators and etc.)

DaGhostman Dimitrov
  • 1,608
  • 20
  • 44
  • 1
    `B` needs to inherit from `A` if you want to access that property. – elclanrs Apr 05 '13 at 22:22
  • B.prototype = new A(); something like this read this it may be useful http://stackoverflow.com/questions/15843660/inheritance-within-javascript – Givi Apr 05 '13 at 22:23
  • and how should I use multiple classes lets say like in a framework(ie. multiple inheritance) – DaGhostman Dimitrov Apr 05 '13 at 22:25
  • related: http://stackoverflow.com/a/15798417/1026459 – Travis J Apr 05 '13 at 22:26
  • The problem is that you're thinking in classes. JavaScript prototype model can sort of imitate class inheritance but not the other way around. Think about modules, that's the JavaScript way. – elclanrs Apr 05 '13 at 22:27
  • try this var foo = (function(foo) { // put all code here... }(foo || {})); and you can read about module patterns from here... http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html – Givi Apr 05 '13 at 22:32
  • @elclanrs ok give me an example of the simple modular usage – DaGhostman Dimitrov Apr 06 '13 at 07:22

2 Answers2

4

You can use inheritance to access the variable.

var A = function() {
    this.myPublicVar = "thisShouldBePrintedFromClassB";
}

A.prototype = {
    showMyVar : function() {alert(this.myPublicVar);} // This gets triggered on direct access.
}

var B = function() {}
B.prototype = new A();
B.prototype.print = function(){
  alert(this.myPublicVar);
}

var b = new B();
b.print();
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1
var A = function() {
    this.myPublicVar = "thisShouldBePrintedFromClassB";
}

A.prototype = {
    showMyVar : function() {alert(this.myPublicVar);} // This gets triggered on direct access.
}

var B = function() {}
B.prototype = new A();  //This is what you're missing.

console.log(B.prototype.myPublicVar);
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124