I don't understand why we need "this" in this case


#1


I was able to solve this exercise, but I'm not sure about the role of "this.name" (or any "this") in this case: For the second part of the assignment, we're supposed to add a function that said

"My name is " + this.name

However, since we don't change the name of the class "Animal", why do we need to put a "this" here? I tried replacing "this.name" with "name" only and changed console.log "Hi my name is "+ this.name" to Hi my name is "+ name" and the code doesn't work. Why?

Below is the code I put for exercise 16:


// create your Animal class here
function Animal(name, numLegs){
    this.name = name;
    this.numLegs = numLegs;
}


// create the sayName method for Animal
Animal.prototype.sayName = function(){
    console.log("Hi my name is " + this.name)
}




// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();


#2

here you create your animal class:

// create your Animal class here
function Animal(name, numLegs){
    this.name = name;
    this.numLegs = numLegs;
}

the parameters (name, numLegs) are added to this. then when you create an instance of your class:

var penguin = new Animal("Captain Cook", 2);

you pass name and 2 as arguments, now this variables are accessible through this

so then you can use this in any method.

you can also do:

function Animal(name, numLegs){
    this.name = name;
    this.numLegs = numLegs;
}


// create the sayName method for Animal
Animal.prototype.sayName = function(name){
    console.log("Hi my name is " + name)
}




// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName("Captain Cook");

methods (sayName) have acccess to self, so that is much easier


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.