jkris jkris - 1 year ago 102
Javascript Question

javascript, can a variable be a value and also a function?

It is possible to code in javascript like the following:

var foo = function(n) { //magic codes };
var bar = foo(2);

bar + 2 // result: 4
bar(2) // result: 4
bar(2)(2) // result: 6

Answer Source

A variable can only hold one value. That value can be a function.

An object can have a toString() method which could be hacked to get close to what you are trying to do.

function myFactory(value) {
  function myFunction(add) {
    return myFactory(value + add);
  myFunction.toString = function() {
    return value;
  return myFunction;

var bar = myFactory(2);

console.log(bar + 2);

This is, of course, horrible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download