为什么 console.log() 只打印成员字段? [英] Why does console.log() only print member fields?
问题描述
如果我运行以下:
var T = function(x, y) {
this.x = x;
this.y = y;
}
T.prototype.foo = function() {
console.log("test");
}
var o = new T(7,4);
o.foo();
console.log(o);
使用 node
我得到:
test
{x: 7, y: 4}
但是如果我在 chrome 中运行它,我会得到:
but if I run it in chrome I get:
test
T {x: 7, y: 4, foo: function}
这只是 log()
方法实现的一种变体,还是为什么在输出中忽略了 prototype
方法?如果它不仅仅是一个 log()
实现案例,这是否意味着将包含字段和方法的对象保存到 mongodb
中是安全的,如果您只想保存领域,即,您可以依赖未考虑的方法吗?
Is this just a variation in the implementation of the log()
method or why are prototype
methods ignored in the output? If its not just a log()
implementation case, does this mean it would be safe to save objects containing both fields and methods into a mongodb
if you only wanted to save the fields, i.e., can you rely on the methods not being considered?
推荐答案
console.log
在不同环境下的实现方式不同.那是因为它所做的只有在查看其结果的工具的上下文中才有意义.在 Chrome 中,您有一个检查器,可以深入到对象中.在 node 中,它将文本输出到命令行,而您在命令行中的功能要少得多.
console.log
is implemented differently in different environments. And that's because what it does only makes sense in the context of the tools that its result are viewed through. In Chrome you have an inspector and can drill into the object. In node, it outputs text to the command line, where you have far less capability.
这纯粹是 console.log
中的一个实现细节,您不应该使用实现的差异来假设对象属性在其他上下文中的工作方式,例如... 将对象写入 mongodb.
This is purely an implementation detail within console.log
and you should not use the difference of implementations to assume anything about how object properties work in other contexts, like say... writing objects to mongodb.
这篇关于为什么 console.log() 只打印成员字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!