javascript – 新手:需要一些关于这个js代码的解释

前端之家收集整理的这篇文章主要介绍了javascript – 新手:需要一些关于这个js代码的解释前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在学习javascript,我已经阅读了somewhere以下代码

  1. if (typeof Object.create !== 'function') {
  2. Object.create = function (o) {
  3. function F() {}
  4. F.prototype = o;
  5. return new F();
  6. };
  7. }
  8. newObject = Object.create(oldObject);

我知道Object.create函数返回一个新对象,该对象继承了作为参数传递给Object.create函数的对象’o’.但是,我不明白这是什么意思呢?我的意思是,即使Object.create函数返回一个新对象,但新对象和旧对象没有区别.即使是新对象继承旧对象,也没有在新对象中定义新方法.那么,在什么情况下我们需要上面的代码获取新对象?

最佳答案
其他几个答案已经在解释这个问题,但我想补充一个例子:

  1. var steve = { eyes: blue,length: 180,weight: 65 };
  2. var stevesClone = Object.create(steve);
  3. // This prints "eyes blue,length 180,weight 65"
  4. for (var property in stevesClone) {
  5. console.log(property,stevesClone[property]);
  6. }
  7. // We can change stevesClone without changing steve:
  8. stevesClone.eyes = "green";
  9. stevesClone.girlfriend = "amy";
  10. // This prints "eyes green,weight 65,girlfriend amy"
  11. for (var property in stevesClone) {
  12. console.log(property,stevesClone[property]);
  13. }
  14. // But if we alter steve,those properties will affect stevesClone as well
  15. // unless they have also been assigned to stevesClone directly:
  16. steve.father = "carl";
  17. steve.eyes = "red";
  18. // So,the clone got steves father carl through inheritance,but keeps his
  19. // green eyes since those were assigned directly to him.
  20. // This prints "eyes green,girlfriend amy,father carl"
  21. for (var property in stevesClone) {
  22. console.log(property,stevesClone[property]);
  23. }

Object.create从现有对象创建一个新对象,并使用原型链来维护它们之间的关系.如果克隆本身没有这些属性,那么来自stevesClone的任何内容都会传播到史蒂夫.因此,对steve的更改可能会影响克隆,但反之亦然.

猜你在找的JavaScript相关文章