object.create 不使用我的新值

object.create doesnt use my new value

本文关键字:我的 新值 create object      更新时间:2023-09-26

我最近发现了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."

person2.print3函数中,您正在访问person.print2() .so 它将始终返回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+"."
}

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

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

当您调用 print3 函数时,也会调用 print2 函数,因此 person2 对象的名字、姓氏、国籍和出生字段将被覆盖。您可能需要将 person2.print3() 修改为:

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