Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the parentheses in function calls optional

Hey, I am about to rewrite the core file for my JavaScript library and I am looking for better ways of doing everything. One of these is how I make parentheses optional, for example some function calls look like this.

Spark('p').content('Hello, World');

And others like this.

Spark.browser();

So I have optional parentheses for the Spark function. Am I right in saying this would be the best way?

window.Spark = function(arg1, arg2) {
    return {
        fn: function() {
            alert('run');
        }
    };
};

for(var f in Spark())
    Spark[f] = Spark()[f];

Spark.fn();
Spark(true, false).fn();

It just seems wrong to me although it is the only method I have come up with that works.

like image 657
Olical Avatar asked Jul 14 '26 09:07

Olical


1 Answers

You're on the right path, but be careful. As it stands, the fn function will be instantiated every time you call Spark(...), which will cause minor performance and memory usage issues.

A cleaner approach would be to use a class and store all those functions in the prototype to avoid unnecessary memory usage:

window.Spark = (function(){

  function inner(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }

  inner.prototype = {
    fn : function() { alert('run') }
  };

  function S(arg1, arg2) { return new inner(arg1, arg2) }

  var dflt = S();
  for (var f in dflt) S[f] = dflt[f];

  return S;
})();
like image 178
Victor Nicollet Avatar answered Jul 15 '26 21:07

Victor Nicollet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!