I have been using Javascript but more in a procedural way not the object oriented way. Recently, I am just getting started to learn Javascript in a OOP manner. Can anybody tell what is the difference between:
var foo = {
method1 : function(){
}
}
and
var foo = function(){
method: function(){
}
}
Are both of these same or is the 1st one static class? If both are same then my 2nd question is how do I write methods and call it statically?
In the first case, you define an object using an object literal. From the view of OOP, it is a singleton.
The other one is syntactically incorrect. What that code probably wanted to resemble, however, is a constructor.
If this
myConstructoris called with thenewkeyword,myConstructorwill run withthisset to reference this new object, so thefieldandmethodproperties will get appended to itExample:
Every new instance of object constructed by
myConstructor()will receive its own copy of the functionmethod. This is wayprototypeis usually used to store functions, but that is out of the scope of this question.As for the static methods, a possibility is to add it directly to the constructor. This is possible, because functions are objects too in JS. Imagine this example.
In this case, the constructor contains an array of all existing instances and methods to manipulate it. These fields and methods may be considered static properties of
myConstructor, because they are included in the constructor (which substitutes classes of the classical OOP) itself and no instantiation is needed to access them.