首页 > 解决方案 > javascript/ 向 repl.it 中的原型添加函数

问题描述

我正在关注本教程

function Bear(type){
  this.type = type;
}

Bear.prototype.growl = function(){
  console.log('grrr')
}

var grizzly = new Bear('grizzly')
var bBear = new Bear('bBear')

console.log(grizzly, bBear, Bear.growl)

结果是:

{
  "type": "grizzly",
  "growl": function(){
  console.log('grrr')
}
} {
  "type": "bBear",
  "growl": function(){
  console.log('grrr')
}
} undefined

但我在repl.it中得到的是:

Bear { type: 'grizzly' } Bear { type: 'bBear' } 

如果我将相同的代码放在 SO 代码片段中,结果是正确的。

为什么我在这里得到不同的结果?

标签: javascriptrepl.it

解决方案


这是不同环境如何记录对象的工件。在 Stack Overflow 上,Stack Snippets 记录对象原型链上任意位置的可枚举属性:

const theProto = { protoProp: 'val' };
const theInstance = Object.create(theProto);
theInstance.instanceProp = 'val';

console.log(theInstance);

Node 中的相同代码仅将属性直接记录在对象上

{ instanceProp: 'val' }

repl.it通过 Node.js 运行代码。

同样,对于您的代码片段,由于该growl属性位于原型对象上,因此当您登录时bBear,您将growl在 Stack Snippet 中看到,但如果您在 Node.js 中运行相同的代码,则不会。

无论您的环境如何,Javascript 中的实际对象都是相同的——您没有做错任何事情。

日志记录行为未标准化。它取决于引擎。


推荐阅读