我读过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({})和.语法来构造对象时,比如enumeration对象。然后打印出来。输出:
{ name: 'Dime', value: 10 } 为什么在node中打印额外的[Number: 10]?但在浏览器控制台,它不会。
我的node版本是v4.2.6和linux。
发布于 2017-06-12 03:15:04
在节点中,console.log()调用util.inspect来获取对象的“人性化”字符串表示,这就是添加[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 }作为参考,下面是节点的实现 of console.log (请注意委托给使用inspect的util.format ):
Console.prototype.log = function log(...args) {
write(this._ignoreErrors,
this._stdout,
`${util.format.apply(null, args)}\n`,
this._stdoutErrorHandler);
};https://stackoverflow.com/questions/44490486
复制相似问题