PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] What is the Javascript equivalent of a Class variable?

 July 08, 2022     class, class-variables, instance, instance-variables, javascript     No comments   

Issue

Edit: Thanks @Aadit M Shah for confirming.

function Apple () {}
Apple.someVar = null; // Class variable
Apple.prototype.someVar = null; // Instance variable

Solution

JavaScript is a functional language and features of classical programming languages are not directly supported but can be achieved by the concept of closures.

In the code snippet you gave, both Apple.someVar and Apple.prototype.someVar will have the same value for all objects created from the Apple constructor function, i.e. like a class variable.

To achieve the functionality of instance variables, use closures. You can look online for more help on closures, here's reference http://javascript.crockford.com/private.html

I am providing a small code snippet to to make it clear.

function Apple(property){
  var color = property.color; //instance variable
  this.getColor = function(){
    return color;
 };  
}
Apple.type = "fruit"; //class variable

var redApple = new Apple({color:'red'});
var greenApple = new Apple({color:'green'});  

both the variables redApple and greenApple share the same property 'type' but each has its own color property.



Answered By - Himanshu Tanwar
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing