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.)

7
  • 1
    B needs to inherit from A if you want to access that property. Commented Apr 5, 2013 at 22:22
  • B.prototype = new A(); something like this read this it may be useful stackoverflow.com/questions/15843660/… Commented Apr 5, 2013 at 22:23
  • and how should I use multiple classes lets say like in a framework(ie. multiple inheritance) Commented Apr 5, 2013 at 22:25
  • related: stackoverflow.com/a/15798417/1026459 Commented Apr 5, 2013 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. Commented Apr 5, 2013 at 22:27

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.