是否有__repr__等价的javascript代码? [英] Is there an __repr__ equivalent for javascript?

查看:86
本文介绍了是否有__repr__等价的javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最接近Python的 repr 的地方是这样:

The closest I got to something close to Python's repr is this:

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即可得到我想要的结果?

Is there a way to represent an object as a string by default? Or am I going to have to just use object.variable to get the results I want?

推荐答案

JSON.stringify 可能是您将从本机库中获得的最接近的.它不适用于对象,但是您可以定义自己的代码来解决该问题.我搜索了提供此功能但找不到任何内容的库.

JSON.stringify is probably the closest you are going to get from native libraries. It doesn't work well with objects, but you could define your own code to work around that. I searched for libraries that provide this functionality but didn't find anything.

这篇关于是否有__repr__等价的javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆