我最接近Python的repr的是这样的:
function User(name, password){
this.name = name;
this.password = password;
}
User.prototype.toString = function(){
return this.name;
};
var user = new User('example', 'password');
console.log(user.toString()) // but user.name would be even shorter
有没有办法在默认情况下将object
表示为字符串?或者我将不得不使用object.variable
来获得我想要的结果?
JSON.stringify
可能是您从本地图书馆获得的最接近的。它不适用于对象,但您可以定义自己的代码来解决这个问题。我搜索了提供此功能但没有找到任何内容的库。
可以通过向该对象添加console.log
方法来覆盖javascript对象的inspect()
表示
例如:
function User(name, password){
this.name = name;
this.password = password;
}
User.prototype.toString = function(){
return this.name;
};
User.prototype.inspect = function(){ return 'Model: ' + this.name ; }
- 感谢'Ciro Santilli'
util.inspect
http://nodejs.org/api/util.html#util_util_inspect_object_options
var util = require('util');
console.log(util.inspect({ a: "0\n1", b: "c"}));
输出:
{ a: '0\n1', b: 'c' }
String(user)
是我能想到的最好的。我认为另一种选择可能是找到第三方库来处理为对象创建人类可读的表示。
正如安德鲁约翰逊所说,JSON.stringify
可能是最接近开箱即用的。
repr的一个常见策略是output runnable Python code。如果你想这样做,lave(eval
对面)是一个不错的选择。
例:
var escodegen = require('escodegen')
var lave = require('lave')
function User(name, password){
this.name = name;
this.password = password;
}
var user = new User('example', 'password');
console.log(lave(user, {generate: escodegen.generate}));
输出(不像我希望的那样优雅!):
var a = Object.create({ 'constructor': function User(name, password){
this.name = name;
this.password = password;
} });
a.name = 'example';
a.password = 'password';
a;
这是NodeJS的解决方案(不确定浏览器)。正如https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_inspect_object_options所说,你可以将inspect(depth, opts)
添加到你的班级,当你console.log(user_class_instance);
时它会被调用
因此,这应该做的伎俩:
User.prototype.inspect = function(depth, opts){
return this.name;
};
Node v6.6.0引入了util.inspect.custom符号:它是一个全球注册的符号,可通过Symbol.for('nodejs.util.inspect.custom')
访问。它可用于声明自定义检查功能。
这是OP案例的用法示例:
function User(name, password){
this.name = name;
this.password = password;
this[Symbol.for('nodejs.util.inspect.custom')] = () => this.name;
}
var user = new User('example', 'password');
console.log(user) // 'example'