3

When creating an object (prior to ES6) one could instantiate an object like so...

var Animal = function(){}

and then

var dog = new Animal();

...

Inside the animal "class" one can add...

var Animal = function( name ){

   this.constructor.prototype.name = name;

}

The question is basically, what is the difference between using the regular this in oppose to using this.constructor.prototype

var Animal = function( name ){

   // what is the difference between this
   this.constructor.prototype.name = name;

   // and that
   this.name = name;

}

I know this kind of basic, if anyone would care to explain. Thanks in advance!

  • 2
    `this.name = name;` assigns value to field of instance. `this.constructor.prototype.name = name;` assigns value to ALL instances' fields `name` – MysterX Nov 27 '17 at 15:34
  • 2
    `this.constructor.prototype` fields are JavaScript's prototypal OOP's equivalent of static fields. – Aaron Nov 27 '17 at 15:34
  • 2
    It's _very_ unlikely that you'd ever want to use the first scenario. – James Nov 27 '17 at 15:36
  • 2
    One simply [does not assign to the prototype inside the constructor](https://stackoverflow.com/questions/28255957/assigning-prototype-methods-inside-the-constructor-function-why-not). And definitely not with dynamic values. – Bergi Nov 27 '17 at 15:36
  • 2
    @Aaron They're not `static` at all. "shared instance properties" would be a proper description. – Bergi Nov 27 '17 at 15:38
  • 2
    @Bergi Looks like the word has multiple meanings. [This](https://en.wikipedia.org/wiki/Static_variable#Object-oriented_programming) is what I meant (rather than the meaning above the linked §) – Aaron Nov 27 '17 at 15:42
  • 1
    Instead of the second i would rather do `Animal.prototype.name = name` – Jonas Wilms Nov 27 '17 at 15:42
  • @MysterX this small comment made a lot of sense after long time of being ignorant thinking this only affects the console.log output (variables are not shown in the top level only) ;P ... thanks, if you would put that in an answer I would give this a right answer.. maybe some other folks could enjoy `this` –  Nov 27 '17 at 15:47
  • @James after reading @MysterXs comment if I understand correctly `this.constructor.prototype` allows you to declare 'shared' variables, I could think of a few situations where this might be handy... something in the vicinity of `dog.applySomethingToAllAnimals()` - pardon the length –  Nov 27 '17 at 15:50
  • 1
    @levi that one line of code breaks so many principles of OOD I wouldn't know where to start. – James Nov 27 '17 at 15:57

0 Answers0