我正在学习javascript,我已经阅读了somewhere以下代码:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldobject);
我知道Object.create函数返回一个新对象,该对象继承了作为参数传递给Object.create函数的对象’o’.但是,我不明白这是什么意思呢?我的意思是,即使Object.create函数返回一个新对象,但新对象和旧对象没有区别.即使是新对象继承旧对象,也没有在新对象中定义新方法.那么,在什么情况下我们需要上面的代码来获取新对象?
最佳答案
其他几个答案已经在解释这个问题,但我想补充一个例子:
var steve = { eyes: blue,length: 180,weight: 65 };
var stevesClone = Object.create(steve);
// This prints "eyes blue,length 180,weight 65"
for (var property in stevesClone) {
console.log(property,stevesClone[property]);
}
// We can change stevesClone without changing steve:
stevesClone.eyes = "green";
stevesClone.girlfriend = "amy";
// This prints "eyes green,weight 65,girlfriend amy"
for (var property in stevesClone) {
console.log(property,stevesClone[property]);
}
// But if we alter steve,those properties will affect stevesClone as well
// unless they have also been assigned to stevesClone directly:
steve.father = "carl";
steve.eyes = "red";
// So,the clone got steves father carl through inheritance,but keeps his
// green eyes since those were assigned directly to him.
// This prints "eyes green,girlfriend amy,father carl"
for (var property in stevesClone) {
console.log(property,stevesClone[property]);
}
Object.create从现有对象创建一个新对象,并使用原型链来维护它们之间的关系.如果克隆本身没有这些属性,那么来自stevesClone的任何内容都会传播到史蒂夫.因此,对steve的更改可能会影响克隆,但反之亦然.
原文地址:https://www.jb51.cc/js/429431.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。