javascript是否有__repr__等价物?

时间:2014-07-23 04:47:52

标签: javascript python node.js

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

8 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:10)

可以通过向该对象添加console.log方法来覆盖

inspect() Javascript对象的表示

例如:

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'

答案 2 :(得分:6)

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

答案 3 :(得分:2)

String(user)

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

答案 4 :(得分:2)

对我来说,一个快捷方式是使用数组文字包装值,如下所示:

console.log([variable]);

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

Screenshot of developer console on Firefox

答案 5 :(得分:0)

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

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

示例:

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;

答案 6 :(得分: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;
};

答案 7 :(得分:0)

节点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'
相关问题