I am a little perplexed about what is going on with my code, here is what I have so far:
function Person(name) {
this.name = name;
}
Person.prototype.getName = this.name;
Person.prototype.displayName = function() {
return this.name;
}
var Sethen = new Person("Sethen");
console.log(Sethen.getName);
console.log(Sethen.displayName());
I am curious as to why getName doesn’t give me the this.name value and only logs blank, while the displayName method gives me the correct value. getName is a property of my prototype object, so my thought process was that I could grab it like this.
Why does getName not log the value of Sethen? How would I go about grabbing that information like a regular property? Must I use a method?
Because the value of
thisisn’t what you think it is when that code is run.thisis probably equal to the global object (i.e.window).Since you’re calling
displayNameand setting the context by prefixing it with an instance of thePersonobject,thisis set correctly inside of the function and you get the person’s name out.Of course, you could always access the
nameproperty directly (Sethen.name).