javascript是否有__repr__等价物?

问题描述 投票:18回答:8

我最接近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来获得我想要的结果?

javascript python node.js
8个回答
19
投票

JSON.stringify可能是您从本地图书馆获得的最接近的。它不适用于对象,但您可以定义自己的代码来解决这个问题。我搜索了提供此功能但没有找到任何内容的库。


9
投票

可以通过向该对象添加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'


5
投票

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' }

2
投票
String(user)

是我能想到的最好的。我认为另一种选择可能是找到第三方库来处理为对象创建人类可读的表示。


2
投票

我的快捷方式是使用数组文字包装值,如下所示:

console.log([variable]);

浏览器开发人员控制台中的输出非常清楚数组的唯一元素是什么。

Screenshot of developer console on Firefox


0
投票

正如安德鲁约翰逊所说,JSON.stringify可能是最接近开箱即用的。

repr的一个常见策略是output runnable Python code。如果你想这样做,laveeval对面)是一个不错的选择。

例:

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;

0
投票

这是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;
};

0
投票

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'
© www.soinside.com 2019 - 2024. All rights reserved.