【问题标题】:Custom value returned by typeoftypeof 返回的自定义值
【发布时间】:2012-11-12 11:46:25
【问题描述】:

有没有办法返回自定义类型而不是“对象”?在下一种情况下,我想返回即“i16”

>function Int16(v) { this.v=v }; var n = new Int16(10);

>typeof n
"object"
>Object.prototype.toString.call(n)
"[object Object]"

【问题讨论】:

  • n instanceof Int16 返回真。不知道这是否有帮助;)
  • 如果不可能,那么我可以添加一个方法来返回值。
  • 除了instanceof我真的不知道还有什么别的办法。同样,在 JS 中实际上不可能实现运算符重载(不幸的是)。
  • @Yoshi,最后我用的是instanceof,谢谢!

标签: javascript typeof


【解决方案1】:

为您的类添加自定义“typeof”属性。然后有一个类似的功能(未经测试):

mytypeof : function (v) {
  type = typeof v;
  return type === "object" && typeof(v["typeof"]) != "undefined" ? v["typeof"] : type;
}

【讨论】:

    【解决方案2】:

    不,你不能重载typeof——它总是返回基类型。

    在给定的示例中,您可以使用构造函数属性:

    function Int16(v) { this.v=v }; 
    > var n = new Int16(10);
    > n.constructor.name
    "Int16"
    > n.constructor === Int16
    true
    

    【讨论】:

    • 虽然我认为这有点帮助,但这里没有返回来自 typeof 的自定义值。
    • 是的,我不喜欢我给出的这个答案。你是对的,当然——我在回答与 OP 不同的问题。我的意思是,也许它让他/她到了正确的地方,但仍然如此。许多道歉。实际答案是“不,typeof 不能重载。您仅获得 System.Type 对象,因此是基本类型(或“对象”)。 (公平地说,看起来 OP 想要 Int16 的类型信息,所以我的答案是对的?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多