object.create不使用我的新值

时间:2015-03-10 10:12:34

标签: javascript

我最近发现了object.create,现在正试图理解它。 但是我没有让它使用我在var person2之后添加的新值。 我的前三个职能部门运作良好。

   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()+".";
}

这部分让我感到困惑,不确定如何使用Object.create

var person2 = Object.create(person);
person2.firstName="Isaac";
person2.lastName="Newton";
person2.nationality="England";
person2.born=new Date("1643-01-04");

我使用person2.print3();打印我的详细信息。 到目前为止,我的理解是我不需要一个新函数来调用它?

我得到了结果:"My name is Albert Einstein from Germany. I was born 1879."这与var person

相同

但它应该是"My name is Isaac Newton from England. I was born 1643."

3 个答案:

答案 0 :(得分:2)

person2.print3功能中,您正在访问person.print2()。因此它将始终返回person object的值。将其更改为this.print2()以获取对象的值,您从中调用函数。更改为print2print3

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+"."
}

答案 1 :(得分:0)

person.print3中你关闭了person变量 - 你没有使用它,而是引用原始人物对象。试试这个:

 person.print3 = function () {   
     return this.print2()+' I was born '+this.born.getFullYear()+".";
 }

答案 2 :(得分:0)

当你调用print3函数时,也会调用print2函数,因此会覆盖person2对象的firstName,lastName,nationality和born字段。 您可能需要将person2.print3()修改为:

person.print3=function(){   
  return "My name is "+this.firstName+" "+this.lastName+" from "+this.nationality+". I was born "+person.born.getFullYear()+".";
}