0

Javascript objects. I am trying to understand the difference between the following ways of class declaration. At a fundamental level is the difference between both of them? Is one advantageous over the other? if so, how?

    1)
        var Animal = function(){
          this.run = function(speed){
             console.log(speed)
           }; 

          this.eat = function(food){
             console.log(food);
           }; 

        }

        var dog = new Animal();

2)
      var Animal = function(){};
      Animal.prototype.run =  function(speed){
             console.log(speed)
           }; 
      Animal.prototype.eat =   function(food){
             console.log(food)
           };  
putvande
  • 15,068
  • 3
  • 34
  • 50
lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • Both do the same. (If you delete var dog = new Animal(); or add it to 2nd block) – Remigijus Pankevičius Feb 28 '14 at 20:35
  • 1
    An advantage of the first way is that you can rename your function by just changing the first line. – almo Feb 28 '14 at 20:37
  • 4
    @r.pankevicius They're similar, but not the same. Instances from each with still have `run` and `eat` methods. But, #1 recreates both methods with every `new` instance. In most cases, each instance doesn't need its own definition, making it a waste of memory. Whereas, #2 lets them be defined once and shared through inheritance. – Jonathan Lonowski Feb 28 '14 at 20:38
  • The link by willlma (http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) tells that "this.x is effectively window.x" in 1st case. What is absolutely insane. – Remigijus Pankevičius Feb 28 '14 at 20:42
  • @Jonathan Lonowski - Yes, I see your point. But Chrome's V8 and FFox translate them to a cheap reference assignment.. Not sure about IE. Anyway it's better to stuck to classic methods. (Upvote) – Remigijus Pankevičius Feb 28 '14 at 20:47
  • @r.pankevicius The comment about "window.x" is about forgetting to `new` an instance (`var dog = Animal()`). The constructor can be called with `this` set to the global object -- `window`, in browsers (`window.eat('Beef')`). – Jonathan Lonowski Feb 28 '14 at 20:48

0 Answers0