前端之家收集整理的这篇文章主要介绍了
javascript – 新手:需要一些关于这个js代码的解释,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
404_0@
我正在学习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的更改可能会影响克隆,但反之亦然.