0

Hello i want to know the difference between this line:

var MyClass={
   init:function(){

   }
}

and

var Myclass=function(){};
Myclass.prototype.init=function(){}
4
  • 1
    One is a class; the other isn't. Commented Feb 19, 2016 at 20:29
  • which is better to use on webpage i'm new in web development so i saw those codes and i want to know better this theme Commented Feb 19, 2016 at 20:34
  • It depends on whether you need a class or an object. Commented Feb 19, 2016 at 20:37
  • @SLaks are you sure that One is a class? or probably second one? One it's a object literal notation. Second constructor function Commented Feb 19, 2016 at 20:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this help me alot

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.