MikeyH
MikeyH

Reputation: 29

What is the purpose of setting "this.name = name;" in JavaScript?

I'm not exactly sure why this is necessary. If I'm taking in a parameter of "name", why can't it be referenced as "name" without first setting it equal to "this.name"?

Forgive my ignorance, I'm new.

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

Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

Upvotes: 0

Views: 5602

Answers (4)

Muhammad Irfan
Muhammad Irfan

Reputation: 294

As use of the pronoun “he.” We could have written this: “John is running fast because John is trying to catch the train.” We don’t reuse “John” in this manner, . In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example:

var person = {
    firstName: "Penelope",
    lastName: "Barrymore",
    fullName: function ()
        ​// Notice we use "this" just as we used "he" in the example sentence earlier?:​
        console.log(this.firstName + " " + this.lastName);
    ​    // We could have also written this:
        console.log(person.firstName + " " + person.lastName);
    }
}

Upvotes: 0

KoolKat
KoolKat

Reputation: 1

Well... you are working with an object constructor and prototype not just a function with two parameters where example:

function Animals(pet1, pet2) {
    var pets = "first pet " + pet1 + " second pet " + pet2;
    console.log(pets);
}
Animals("Tiger", "Lion");

so referencing to your parameter as 'this.name' is a prototype of the sayName() if you know what i mean. FOR MORE.

Upvotes: 0

Muhammad Kashif Nazar
Muhammad Kashif Nazar

Reputation: 23865

this.name represents the instance variable while the name variable is a parameter that is in the scope of the function (constructor in this case).

With this assignment, the value of the local variable is assigned to the instance variable.

Upvotes: 2

renno
renno

Reputation: 2827

This is not a javascript thing, it's an OOP thing. You want to leave the properties of an object isolated from other scopes.

var Animal = function(name) {
    this.name = name;
};
var name = "foo";
var dog = new Animal("bar");
// shows "foo"
console.log(name);
// shows "bar"
console.log(dog.name);

Upvotes: 1

Related Questions