Pergunta

I made a more accurate typeof-function and want to use it like the default typeof-operator. Currenty I call my typeOf()-function like every other function: typeOf("foo"), however is it possible to get the function arguments without defining them in its parens? Like the typeof-operator.

default: typeof "foo" === "string"

desired: typeOf "foo" === "string"

What I've tried is to define and override a global variable, works but yeah, not really a solution:

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

console.log(typeOf); // "string"
Foi útil?

Solução

...is it possible to get the function arguments without defining them in its parens?

No, it isn't. That would require that JavaScript allow you to create a new operator, rather than function, which isn't a feature the language has. (There are two functions — toString and valueOf — that can get called implicitly on an object as part of an expression, but that wouldn't help you here.)

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top