0

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"
yckart
  • 32,460
  • 9
  • 122
  • 129
  • You are asking for functions to behave the same as operators (`typeof` is a unary operator). This is unfortunately not possible in Javascript, as operators are part of the language, and you cannot define your own. – Frédéric Hamidi Mar 25 '13 at 18:34
  • @FrédéricHamidi Ok, that's the badass-part in javascript ;-) Thanks! – yckart Mar 25 '13 at 18:35
  • 1
    You can use [coffeescript](http://coffeescript.org/#try:typeOf%20%3D%20(x)%20-%3E%20%22whatever%20you%20want%22%0A%0AtypeOf%20%22string%22) :) – Ben McCormick Mar 25 '13 at 18:35

2 Answers2

2

...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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
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.

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71