Hello i want to know the difference between this line:
var MyClass={
init:function(){
}
}
and
var Myclass=function(){};
Myclass.prototype.init=function(){}
Hello i want to know the difference between this line:
var MyClass={
init:function(){
}
}
and
var Myclass=function(){};
Myclass.prototype.init=function(){}
var MyClass={
init:function(){
}
}
defines an object called MyClass with a member function init. This is object literal notation.
There is only single instance of this object; you can't create a new one.
You can only say for example
MyClass.init();
you can't say
var foo = new MyClass(); (this will cause an error)
On the other hand,
var Myclass=function(){};
Myclass.prototype.init=function(){}
is different; it defines a "class" (or constructor function as it can be called) which has a function init but which you can create multiple instances of; each instance will have the init() function.
var foo = new Myclass();
var bar = new Myclass();
foo.init();
bar.init();
So which you use really depends on what you need it for; if you're making an object that has some utility functions or maybe represents a service which only needs a single copy ever, the first is fine; whereas if you need to be able to make multiple instances because each instance's data might need to change indepdendently, use the second.