Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 由typeof返回的自定义值_Javascript_Typeof - Fatal编程技术网

Javascript 由typeof返回的自定义值

Javascript 由typeof返回的自定义值,javascript,typeof,Javascript,Typeof,有没有办法返回自定义类型而不是“对象”?在下一个案例中,我想返回,即“i16” 向类中添加自定义的“typeof”属性。然后有一个类似(未测试)的函数: 不,您不能重载typeof——它总是返回基本类型 在给定的示例中,可以使用构造函数属性: function Int16(v) { this.v=v }; > var n = new Int16(10); > n.constructor.name "Int16" > n.constructor === Int16 true

有没有办法返回自定义类型而不是“对象”?在下一个案例中,我想返回,即“i16”

向类中添加自定义的“typeof”属性。然后有一个类似(未测试)的函数:


不,您不能重载
typeof
——它总是返回基本类型

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

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

n instanceof Int16
返回true。不知道这是否有帮助;)如果不可能,那么我可以添加一个方法来返回值。除了使用
instanceof
之外,我真的不知道还有其他方法。同样,在JS中操作符重载是不可能的(很不幸)。@Yoshi,最后我使用的是
instanceof
,谢谢!虽然我觉得这有点帮助,但这里没有任何东西可以从
typeof
返回自定义值。哎呀,我不喜欢我给出的这个答案。当然,你是对的——我回答的问题与OP的不同。我的意思是,也许这让他/她到了正确的地方,但仍然如此。很多道歉。实际答案是“不,
typeof
不能重载。您只获得System.Type对象,因此是基类型(或“对象”)(公平地说,它看起来像是Int16的OP想要的类型信息,所以我的答案有点正确?)
mytypeof : function (v) {
  type = typeof v;
  return type === "object" && typeof(v["typeof"]) != "undefined" ? v["typeof"] : type;
}
function Int16(v) { this.v=v }; 
> var n = new Int16(10);
> n.constructor.name
"Int16"
> n.constructor === Int16
true