0

I understand that there are two ways of creating classes in JavaScript

var MyObj = function(val)
{
  this.vari = val;
}

Where val will be a non static member.

Whereas,

var MyObj = new Object();
MyObj.vari = "";

This is a single object so members of it here will act like static members. My question is that how do we have both static as well as non static content in same class?

3 Answers 3

3

There are no classes in JavaScript, only objects.

When you create a new object you are "extending" from the function's prototype, not the function itself. In order to make a variable or function appear to be static you would have to attach it to the function used to create the object, and not its prototype.

js> var Foo = function(){ this.member = "member"; };
js> Foo.staticMember = "staticMember";
js> var f = new Foo();

js> Foo.member;
undefined
js> Foo.staticMember;
"staticMember"
js> f.member;
"member"
js> f.staticMember;
undefined
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. By the way is that Rhino?
Sort of. I really just typed it in for example purposes, but I mimicked the Rhino repl.
2

Using your first example:

var MyObj = function(val) {
  this.vari = val;
};

MyObj.var2=value;

Will create a new "static" property callable as:

var o = MyObj.var2;

Comments

1

The first one initializes the MyObj variable with the anonymous function - it does not create the class. The MyObj may be later used as the object constructor that initializes one object field - vari. There is nothing "statis" in OOP meaning.

The second one creates the object of the Object type and initializes its property. Again, there is nothing static.

In OOP "statis" means the member of the class, e.g. variables and objects that belong to class definition. For example, the following schema demonstrates this concept:

function MyClass() {
  this.objectProperty = "I'm object property";
  // the following demonstrates initialization of
  // the object property from class (static) property:
  this.varFromStatic = MyClass.classProperty;
}
MyClass.classProperty = "I'm class (static) property";

var obj = new MyClass();
// now obj.varFromStatic contains "I'm class (static) property"

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.