object.create 不使用我的新值
object.create doesnt use my new value
我最近发现了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()
以获取对象的值,从中调用函数。更改为print2
和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+"."
}
在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()+".";
}
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 可以't使我的文本值在查询中起作用
- AngularJs/GitHub :如何在没有任何历史记录的情况下将角度种子克隆到我的新项目中
- object.create 不使用我的新值
- 为什么获胜't我的输入值总和
- 我的输入值'对话框窗体上的s;t更新
- ng模型没有更新我的对象值
- 如何从javascript文件中获取值并更新正则表达式中的新值
- 在按键时获取输入字段的新值
- 我的新窗口无法运行
- 有没有办法使用变量的新值动态重新加载 ASS
- 确保我的随机值数组不包含重复值
- 为什么我的 HTML 按钮刷新页面?/为什么我不能让我的新 HTML DOM 元素插入到我的页面中
- var.push 并在 HTML 页面中显示我的新临时信息
- 数组的旧值替换为数组的新值
- 为什么我的布尔值不会改变
- 范围 .$watch 中的新值未定义
- 如何使用Angular$location通过动态更改其键值params来设置我的新url位置
- 我如何更新javascript变量的新值在我的数据库中发生变化