5

我想知道是否有任何方法可以覆盖typeof操作员的行为。具体来说,我想在typeof同时调用运算符时返回“字符串”foo = "hi"bar = new String("hi")

typeof bar返回“对象”,但我希望它返回“字符串”。

我知道这可以通过声明我自己的函数或访问构造函数名称来完成,但我想修改typeof运算符的行为。

编辑 -我正在寻找一些可以在程序开头添加的代码,这些代码可以修改程序其余部分中所有 typeof 运算符的行为。

4

4 回答 4

5

那是不可能的。本机运算符的行为无法更改。

相关链接:

于 2013-06-27T03:02:45.410 回答
2

您无法更改 Javascript 运算符,但是您可以检查它是字符串还是带有instanceof.

var strObj = new String('im a string')
var str = 'im a string'

alert(strObj instanceof String); //true
alert(typeof strObj == 'string'); //false
alert(str instanceof String); //false
alert(typeof str == 'string'); //true
alert(strObj instanceof String || typeof strObj == 'string'); //true
alert(str instanceof String || typeof str == 'string'); //true

当然,创建自己的函数要简单得多,但如果你想使用原生JS,那就是这样:alert(str instanceof String || typeof str == 'string');

于 2013-06-27T03:05:51.737 回答
1

typeof 是 JavaScript 中的运算符,所以我很确定你不能。要检测某个东西是否是字符串,您可以使用以下内容:

var s = "hello";
console.log(s.substr&&s.charAt&&s.toUpperCase==="".toUpperCase)//true
s = new String("hello");
console.log(s.substr&&s.charAt&&s.toUpperCase==="".toUpperCase)//true
于 2013-06-27T02:54:24.503 回答
0

不,您不能就此修改typeof操作员或任何其他操作员的行为。然而,下一个最佳解决方案是使用Object.prototype.toString如下:

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

现在您可以按如下方式使用它(参见演示 - http://jsfiddle.net/CMwdL/):

var foo = "hi";
var bar = new String("hi");

alert(typeOf(foo)); // String
alert(typeOf(bar)); // String

这个工作的原因在以下链接中给出:http: //bonsaiden.github.io/JavaScript-Garden/#types.typeof

于 2013-06-27T02:58:00.997 回答