【问题标题】:js: Object returning human readable stringjs:返回人类可读字符串的对象
【发布时间】:2017-07-07 18:38:00
【问题描述】:

是否可以创建一个对象以返回人类可读的字符串?

function hsl_obj(h, s, l) {
    this.h = h;
    this.s = s;
    this.l = l;
    this.__str__ = function() {
        return "hsl(" + this.h + ", " + this.s + "%, " + this.l + ")";
    }
}

var badass = new hsl_obj(76, 64, 59); // #BADA55
console.log(badass); // --> hsl(76, 64%, 59%)
console.log(badass.h); // --> 76
console.log(badass.s); // --> 64
console.log(badass.l); // --> 59

$("p").css("background-color", badass);
$("#ph").html(badass.h);
$("#ps").html(badass.d);
$("#pl").html(badass.l);

我知道我可以将__str__ 更改为toString 并改用badass.toString(),但我想知道这种方法是否可行。这有点像python中的__str__方法。

编辑

现在当我调用badass 时,它返回hsl_obj {h: 76, s: 64, l: 59}

【问题讨论】:

  • 也许JSON.stringify(obj); ?
  • 正要说同样的话,因为问题有点奇怪:)
  • 什么时候应该返回字符串?
  • 同意 mrlew.. 使用 JSON.stringify(obj) 这将为您提供对象的 json 字符串

标签: javascript function tostring


【解决方案1】:

你想要 PrettyPrint.js

https://github.com/padolsey-archive/prettyprint.js

我有一个书签可以在任何页面上转储window

javascript:!function(){var t=document.createElement("script");t.setAttribute("src","https://rawgit.com/padolsey-archive/prettyprint.js/master/prettyprint.js"),document.head.appendChild(t),t.onload=function(){var t=prettyPrint(window);document.body.innerHTML="",document.body.insertBefore(t,document.body.firstChild)}}();

【讨论】:

    【解决方案2】:

    您的问题有点令人困惑,只要您调用方法badass.__str__(),它就会按照您的方式工作如果您不想调用该函数来获取字符串值,您可以尝试设置getter对于__string__ 像这样:

    function hsl_obj(h,s,l) {
      this.h = h;
      this.s = s;
      this.l = l;
    }
    Object.defineProperty(hsl_obj.prototype, '__str__', {
      get: function() {
        return "hsl(" + this.h + ", " + this.s + "%, " + this.l + ")";
      }
    })
    
    var badass = new hsl_obj(76, 64, 59);
    console.log(badass.__str__) // --> "hsl(76, 64%, 59)"
    

    【讨论】:

      【解决方案3】:

      我认为这里的混淆是您期望 console.log() 总是期望一个字符串,但它会接受任何类型并尝试表示它。

      因此,当您将对象传递给它时,它会向您显示该对象。 也许使用console.log(badass + ''); 会得到你所期望的结果?

      虽然这个问题令人困惑,但我认为它需要更具体。 我只是以我自己的方式解释这个问题......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-22
        • 2015-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        • 2015-09-17
        • 1970-01-01
        相关资源
        最近更新 更多