0

I'm not able to understand what exactly is the difference by defining the function inside the class function & defining it as prototype. Here is my code.

PART 1

function myContent() {

    this.toUserID = "1234";
    this.loadMainLabel = function(url) {
        alert("url:"+url);
    }       
}

var objMyContent = new myContent();
objMyContent.loadMainLabel("www.google.com");

PART 2

function myContent() {

    this.toUserID = "1234";          
}

var objMyContent = new myContent();
myContent.prototype.loadMainLabel = function(url) {
    alert(url);
}
objMyContent.loadMainLabel("www.google.com");

Both gives the same output.. But, what exactly is the difference? Any thoughts would be appreciable.

Cheers!

Syed
  • 2,471
  • 10
  • 49
  • 89

1 Answers1

-1

You are defining the object as a prototype in both cases. In several other languages, you define a class for an object (Not an object itself) and then create objects as instances of that class.

  • Class

    Define methods and properties, but is different from an instance of that class. Objects are then created as instances of the class.

  • Prototype

    Define a prototype object and then create spin-off objects from that prototype. The prototype is an example of that kind of object rather than a definition of that kind of object.

See this MDN page for a more detailed explanation of the difference

neelsg
  • 4,802
  • 5
  • 34
  • 58
  • This subject has been answered over and over again, already. Please just mark it as [an duplicate](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript), as there are plenty of excellent answers out there. – Cerbrus Jun 17 '14 at 08:13