node.js用额外的字段打印自定义枚举对象,如{ name:'Dime',value:10}

我已阅读JavaScript权威指南,这里是第9.6.2章的enumeration class

 function inherit(p) { if (p == null) throw TypeError(); // p must be a non-null object if (Object.create) // If Object.create() is defined... return Object.create(p); // then just use it. var t = typeof p; // Otherwise do some more type checking if (t !== "object" && t !== "function") throw TypeError(); function f() {}; // Define a dummy constructor function. f.prototype = p; // Set its prototype property to p. return new f(); // Use f() to create an "heir" of p. } function enumeration(namesToValues) { // This is the dummy constructor function that will be the return value. var enumeration = function() { throw "Can't Instantiate Enumerations"; }; // Enumerated values inherit from this object. var proto = enumeration.prototype = { constructor: enumeration, // Identify type toString: function() { return this.name; }, // Return name valueOf: function() { return this.value; }, // Return value toJSON: function() { return this.name; } // For serialization }; enumeration.values = []; // An array of the enumerated value objects // Now create the instances of this new type. for (var name in namesToValues) { // For each value var e = inherit(proto); // Create an object to represent it e.name = name; // Give it a name e.value = namesToValues[name]; // And a value enumeration[name] = e; // Make it a property of constructor enumeration.values.push(e); // And store in the values array } // A class method for iterating the instances of the class enumeration.foreach = function(f, c) { for (var i = 0; i < this.values.length; i++) f.call(c, this.values[i]); }; // Return the constructor that identifies the new type return enumeration; } var Coin = enumeration({ Penny: 1, Nickel: 5, Dime: 10, Quarter: 25 }); var c = Coin.Dime; // This is an instance of the new class console.log(c); // => { [Number: 10] name: 'Dime', value: 10 } // Construct other object with `name` and `value`. var o = Object.create({}); o.name = 'Dime'; o.value = 10; console.log(o); // => { name: 'sam', value: 10 } 

当我在node上运行它时,代码的输出是

 { [Number: 10] name: 'Dime', value: 10 } 

但是当我用Object.create({})和构造一个对象o . 类似于enumeration对象的语法。 然后打印出来。 输出:

 { name: 'Dime', value: 10 } 

为什么在node上打印额外的[Number: 10] ? 但在浏览器控制台,它不会。
我的node版本是v4.2.6linux

在节点中, console.log()调用util.inspect来得到对象的“人性化”string表示,这就是[Number: 10] ,因此与浏览器的输出有所不同。

关于为什么节点为枚举和POJO发出[Number: 10] ,请注意,枚举的原型定义了valueOf ,它旨在为对象提供一个原始值。

添加valueOf到POJO的原型将会发出[Number: 10]

 pojoProto = { valueOf : function() { return this.value; } }; pojo = inherit(pojoProto); pojo.name = 'Dime'; pojo.value = 10; console.log(pojo); //{ [Number: 10] name: 'Dime', value: 10 } 

作为参考,这里是节点的console.log 实现 (注意使用inspect util.format委托):

 Console.prototype.log = function log(...args) { write(this._ignoreErrors, this._stdout, `${util.format.apply(null, args)}\n`, this._stdoutErrorHandler); };