So, now basically the “example” var acts as a function and as an object at the same time.
It does not act as a function and an object, but a function and an object. Functions are objects in JavaScript.
This raised some questions for me, one of which is why
Mostly because what Eih decided to do in those 10 days in May 1995. Why he decided that this is only what he can answer, but over the years there have been many languages that also see no reason to consider functions as something special and different. Probably influenced by those. It is incredibly convenient and flexible that functions are the right objects. For example:
function foo() {
I can use the variable f to mean foo , because foo is an object. In many languages, such as Java, it is a real pain to do this (although Java is now slightly better thanks to the recently added lambdas).
Since functions are objects, they have a prototype, which means that I can add functions to all functions. For example: it’s very convenient for me to be able to use the function and “bake” (or “ curry ”) the arguments:
// A simple function function foo(a, b) { console.log("a is " + a); console.log("b is " + b); } // Create a new one that, when called, will call the original passing in // 1 as the first argument and then passing in any further arguments, // preserving the `this` it was called with var f = foo.curry(1); // Call it f(2); // "a is 1" / "b is 2"
Since JavaScript does not have a curry function (it has a bind , which is similar but interferes with this ), I can add one:
var slice = Array.prototype.slice; Object.defineProperty(Function.prototype, "curry", { value: function() { var f = this; var args = slice.call(arguments); return function() { return f.apply(this, args.concat(slice.call(arguments))); }; } });
And voilà, now I can use curry for any function:
var slice = Array.prototype.slice; Object.defineProperty(Function.prototype, "curry", { value: function() { var f = this; var args = slice.call(arguments); return function() { return f.apply(this, args.concat(slice.call(arguments))); }; } });
<script src="//tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
is there any way to do this by creating an object literal
No, the only way to create a function is to start with a function. You cannot take a non-functional object and turn it into a function.