javascript - 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 代码片段中,结果是正确的。
为什么我在这里得到不同的结果?
解决方案
这是不同环境如何记录对象的工件。在 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 中的实际对象都是相同的——您没有做错任何事情。
日志记录行为未标准化。它取决于引擎。
推荐阅读
- javascript - JavaScript:我在这个例子中对 let 的解释正确吗?
- c# - 秒表 c# 游戏
- spring-boot - JPA CriteriaQuery 无法为日期差异之和找到适当的构造函数
- recursion - Erlang理解递归:递归查找子字符串是否是字符串的前缀
- c# - 制作各种搜索引擎,我被困住了
- .net - .NET 和 Python 之间的两种方式通信
- python - 如何使用 Python 子进程打开另一个 Python 文件?
- mvvm - 通过 getter 访问 ViewModelFactory 对象或作为构造函数参数传递给 ViewModels?
- android - 使用自定义模型时如何解决张量流形状问题?
- sql - 我如何根据产品代码和销售它的卖家获得数量的总和