简体   繁体   English

javascript/ 添加 function 到 repl.it 中的原型

[英]javascript/ add function to prototype in repl.it

I am following this tutorial .我正在关注本教程

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)

the result of this sould be:结果是:

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

but what I get in repl.it is:但我在repl.it中得到的是:

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

If I put the same code in a SO code snippet, the result is correct.如果我将相同的代码放在 SO 代码片段中,结果是正确的。

Why do I get different results here?为什么我在这里得到不同的结果?

This is an artifact of how different environments log objects.这是不同环境如何记录对象的工件。 On Stack Overflow, Stack Snippets log enumerable properties anywhere on the prototype chain on the object:在 Stack Overflow 上,Stack Snippets 记录 object 原型链上任意位置的可枚举属性:

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

The same code in Node only logs the properties directly on the object : Node 中的相同代码仅将属性直接记录在 object 上

{ instanceProp: 'val' }

And repl.it runs the code through Node. repl.it通过 Node 运行代码。

Similarly, with your snippet, since the growl property is on the prototype object, when you log bBear , you'll see growl in a Stack Snippet, but not if you run the same code in Node.同样,对于您的代码片段,由于growl属性位于原型object 上,因此当您登录bBear时,您会在 Stack Snippet 中看到growl ,但如果您在 Node.js 中运行相同的代码则不会。

The actual object in Javascript is the same regardless of your environment - you're not doing anything wrong.无论您的环境如何,Javascript 中的实际 object 都是相同的 - 您没有做错任何事情。

Logging behavior is not standardized.日志记录行为未标准化。 It's engine-dependant.它取决于引擎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM