【问题标题】:What is the reason for this confusing log information about JavaScript objects in Chrome DevToolsChrome DevTools 中有关 JavaScript 对象的日志信息令人困惑的原因是什么
【发布时间】:2013-10-31 13:16:37
【问题描述】:

如果我运行这个,例如在 jsFiddle 中:

function Animal() {
}

var animal = new Animal();

console.log(animal);
console.log(Animal.prototype);
console.log(animal.__proto__);

然后我在 Chrome 的 DevTool 窗口的控制台中得到这些结果 (3x Animal {}):

Animal {} (index):26
Animal {} (index):27
Animal {} (index):28

在我看来这很令人困惑,因为我们知道只有 Animal.prototypeanimal.__proto__ 在这种情况下指向同一个对象。还是有合理的理由这样做?

【问题讨论】:

  • 好问题。你会提出什么替代方案?
  • 你说的是数字吗? 26, 27, 28?
  • @thefourtheye 他说日志(动物)显示为Animal {}。也许应该删除数字以使其更清晰。
  • @thefourtheye no :),我说的是 3x Animal {}
  • @Tibos 我已经扩展了我的问题以使其更清楚。

标签: javascript google-chrome


【解决方案1】:

它将它显示为一个对象,并在其中显示它的所有属性。在这种情况下,由于没有,它显示为空白。但是,如果我们在方法中添加一个属性,那么

function Animal() {
    this.foo="bar";
}

var animal = new Animal();

console.log(animal);
console.log(Animal.prototype);
console.log(animal.__proto__);

我们得到:

Animal {foo: "bar"}
Animal {}
Animal {}

编辑:误读问题

来自MDN: 当一个对象被创建时,它的 proto 属性被设置为引用与其内部 [[Prototype]] 相同的对象(即它的构造函数的原型对象)。为 proto 分配新值也会更改内部 [[Prototype]] 属性的值,除非对象不可扩展。

【讨论】:

  • 问题的重点是:为什么animalanimal.__proto__都是Animal类型的?
  • @Tibos 已编辑以反映 OP 的帖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 2010-09-28
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多