0

我做了一个更准确的typeof-function 并希望像默认typeof-operator 一样使用它。typeOf()目前,我像其他所有函数一样调用我的 -function : typeOf("foo"),但是是否可以在不在其括号中定义它们的情况下获取函数参数?就像typeof- 运算符一样。

默认:typeof "foo" === "string"

想要的:typeOf "foo" === "string"

我尝试的是定义和覆盖一个全局变量,可以,但是是的,不是真正的解决方案:

window.typeOf = "foo";
(function(window) {
    window.typeOf = (Object.prototype.toString.call(window.typeOf).match(/\[object (.+)\]/)[1] + "").toLowerCase();
}(this));

console.log(typeOf); // "string"
4

2 回答 2

2

...是否可以获取函数参数而不在其括号中定义它们?

不,不是。这将要求 JavaScript 允许您创建一个新的operator,而不是 function,这不是该语言所具有的功能。(有两个函数——toStringvalueOf ——可以作为表达式的一部分在对象上被隐式调用,但这在这里对你没有帮助。)

于 2013-03-25T18:34:27.560 回答
0

No this is not possible in normal javascript. You can't define custom operators, only objects and therefore functions. You also can't change javascripts syntax for calling functions.

If you really want to use syntax like this you can use coffeescript and write code like this

typeOf = (x) -> "whatever you want"

typeOf "string"

which will translate to javascript like this

var typeOf;

typeOf = function(x) {
  return "whatever you want";
};

typeOf("string");

Example

But there's no way to replicate that in pure javascript.

A quick aside

One more note: I wouldn't advise naming this operator typeOf even if you did have it. Naming 2 things that act similarly but act slightly different the same thing other than a single capitalized letter is just begging for subtle typo errors that are hard to trackdown and check. Something like exactType or something else different would remove the potential confusion/bugs.

于 2013-03-25T18:40:13.777 回答