3. Displaying People - thought "this" would work


#1


Initially, I thought using "this" to reference the object passed as the argument would work inside the function, but it apparently does not in our course's environment. Can someone confirm that "this" could not be used in this lesson.

Thank you.


// use of "this"
var printPerson = function(person) {
    console.log(this.firstName + " " + this.lastName);
};

// use of parameter; "person"
var printPerson = function(person) {
    console.log(person.firstName + " " + person.lastName);
};


#2

Kind of strange to a have a parameter that you ignore, isn't it?

So which value are you operating on and where should it be coming from? How is it provided?

As you can see here, your function can be used. The question is, how do you want to use it?

var printPerson = function(person) {
    console.log(this.firstName + " " + this.lastName);
};

myObj = {firstName: 'bob', lastName: 'bobbobobob', print: printPerson}
myObj.print();  // bob bobbobbob

And obviously, it shouldn't have unused parameters.


#3

Thanks again for the responses.

Are you saying that both versions would work; be acceptable practices?


#4

It certainly isn't acceptable to have a parameter that you ignore. That's saying: You have to give me a value, but I won't bother to look at it. Kinda rude really.

Go read up on this and then see if you still have questions after that.


#5

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