-1

I am a javascript novice and I don't understand why 'this' is used as a parameter alongside the actual parameter for calling a prototype... In the image provided you can see an example of its use. So why is it necessary to add 'this' as a parameter? What does it do exactly?

'use strict';
function Animal(voice){
this.voice = voice || 'grunt'
}

Animal.prototype.speak = function(){
 display(this.voice)
}

function Cat(name, color){
 Animal.call(this, 'Meow')
 this.name = name
 this.color = color
}

Cat.prototype = Object.create(Animal.prototype)

var Fluffy = new Cat('Fluffy', 'White')

Fluffy.speak()

enter image description here

Ka ri ma
  • 13
  • 4
  • 6
    Don't show **pictures** of code. Show code. More: meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 – T.J. Crowder Nov 24 '16 at 12:52
  • If you include a copy of the HTML code where you initiate the function calls it will help to answer your question in the most relatable way to your project :) – amyloula Nov 24 '16 at 12:54
  • call and apply are a way to pass the reference for which the function is called it sets the calling reference – Vinod Louis Nov 24 '16 at 12:55

1 Answers1

4

This

Animal.call(this, 'Meow');

...is used so that within the call to Animal, this will refer to the same thing it refers to within Cat, so that Animal sets up its instance properties on that same instance. If you just did Animal('Meow'), when Animal wrote to this.voice, it would either throw an error (in strict mode) or add a global variable called voice (in loose mode), neither of which is a desired outcome.

More:

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639