0

What is the difference between defining classed in the following ways?

1)

var parentCls = {
    name:'John',
    callMe : function (){
        alert('Method gets called');
    }
}
parentCls.callMe();

2)

function parentCls(){
    this.name='John';
    this.callMe = function (){
        alert('Method gets called');
    }
}
parentCls.CallMe()

Thanks

user385729
  • 1,924
  • 9
  • 29
  • 42
  • Thansk for the link! So now my question is also what is the difference between :1)var functionOne = function() { // Some code }; 2) var functionOne = { // Some code }; – user385729 May 06 '14 at 23:32
  • 2
    Second is not a function, but an object – Colandus May 06 '14 at 23:39
  • Your second snippet is an error. – Chuck May 06 '14 at 23:44
  • It's a bit misleading to talk about "classes" in JavaScript (even though ES6 will finally use the `class` keyword). JavaScript has objects and constructor functions, which create objects. – Felix Kling May 07 '14 at 00:15

2 Answers2

3

This is an object:

var parentCls = {
    name:'John',
    callMe : function (){
        alert('Method gets called');
    }
}
parentCls.callMe();

This is a function:

function parentCls(){
    this.name='John';
    this.callMe = function (){
        alert('Method gets called');
    }
}
parentCls.callMe()

In this code, you will receive an error. You can't access parentCls.callMe()

More here: javascript : function and object...?

Community
  • 1
  • 1
Colandus
  • 1,634
  • 13
  • 21
  • sorry I forgot to add: var obj = new parentCls(); obj.callMe(); So why this video (https://www.youtube.com/watch?v=PMfcsYzj-9M) at 13:20 says AnswerPrototype is a class? Is it a typo? – user385729 May 06 '14 at 23:48
  • It's not a typo, a class is practically an object. – Colandus May 06 '14 at 23:51
0

Usually you use function parentCls() if you have something to pass to it. For example

function parentCls(name){
    this.name=name;
    this.callMe = function (){
        alert('Method gets called');
    }
}

So you can create an object like var newObject = new parentCls('abc');