Reputation: 33
I've recently found out about object.create and is now trying to understand it.
But I'm not getting it to use my new values I've added after var person2
.
My first three functions are working great.
var person = {}
person.print1=function(){
this.firstName="Albert"
return "My name is "+this.firstName+"."
};
person.print2=function(){
this.lastName="Einstein";
this.nationality="Germany";
return "My name is "+this.firstName+" "+this.lastName+" from "+this.nationality+"."
}
person.born=new Date("1879,03,14");
person.print3=function(){
return person.print2()+' I was born '+person.born.getFullYear()+".";
}
This part is where I get confused and unsure of how to use Object.create
var person2 = Object.create(person);
person2.firstName="Isaac";
person2.lastName="Newton";
person2.nationality="England";
person2.born=new Date("1643-01-04");
I use person2.print3();
to print my details.
My understanding so far is that I don't need a new function to call this?
I get the result: "My name is Albert Einstein from Germany. I was born 1879."
Which is the same I get from var person
But it should be "My name is Isaac Newton from England. I was born 1643."
Upvotes: 0
Views: 51
Reputation: 571
Inside the person2.print3
function your are accessing person.print2()
.so it will always return person object
's values.change that to this.print2()
to get values of object,from which you are calling the function.changes to print2
and print3
person.print3=function(){
return this.print2()+' I was born '+this.born.getFullYear()+".";
}
person.print2=function(){
//this.lastName="Einstein";
//this.nationality="Germany";
return "My name is "+this.firstName+" "+this.lastName+" from "+this.nationality+"."
}
Upvotes: 2
Reputation: 532
when you call the print3 function, the print2 function is called too and therefore the firstName, lastName, nationality and born fields of the person2 object are overwritten. You may need to modify the person2.print3() to:
person.print3=function(){
return "My name is "+this.firstName+" "+this.lastName+" from "+this.nationality+". I was born "+person.born.getFullYear()+".";
}
Upvotes: 0
Reputation: 2657
In person.print3
you're closing over the person
variable - you're not using this but instead referring to the original person object. Try this:
person.print3 = function () {
return this.print2()+' I was born '+this.born.getFullYear()+".";
}
Upvotes: 0