是否有一个__repr__相当于JavaScript?
最接近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
作为默认的string? 或者我将不得不使用object.variable
来获得我想要的结果?
JSON.stringify
可能是最接近你从本地库中获得的。 它不适用于对象,但你可以定义自己的代码来解决这个问题。 我search提供此function的库,但没有find任何东西。
可以通过向该对象添加inspect()
方法来重写Javascript对象的console.log
表示forms
例如:
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
是一种可能性:
var util = require('util'); console.log(util.inspect({ a: "0\n1", b: "c"}));
输出:
{ a: '0\n1', b: 'c' }
String(user)
是我能想到的最好的。 我认为另一种select可能是find一个第三方库,处理为对象创build人类可读的表示。
正如安德鲁·约翰逊所说, JSON.stringify
可能是你可以从盒子里得到最接近的。
repr的一个常见策略是输出可运行的Python代码 。 如果你想这样做, lave (对eval
)是一个不错的select。
例:
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;
对我来说,一个快捷方式是用数组文字包装值,如下所示:
console.log([variable]);
浏览器的开发者控制台中的输出很清楚数组的唯一元素是什么。