Make parentheses optional in function calls

Hey, I'm going to rewrite the main file for my JavaScript library, and I'm looking for better ways to do everything. One of them is that I make the brackets optional, for example, some function calls look like this.

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

And others like it.

Spark.browser();

So, I have optional parentheses for the Spark function. Am I saying this is 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 seems to me that this is wrong, although this is the only method that I came up with for this.

+3
source share
2 answers

, . , fn , Spark(...), .

, :

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;
})();
+1

, , ? JavaScript (, VB Delphi), ( - ) ? JavaScript , , . , , .

, , . :

function MyClass(Parameter /*optional*/)
{
  // Initialization (optional)
  this.anyProperty = parameter;

  this.anyMethod = function(p)
  {
    alert(p);
  }
}

// Or declare methods like this (faster and more efficient)
MyClass.prototype.anyMethod2 = function(p)
{
  alert(p);
}

:

var c = new MyClass;
c.anyMethod2('Hello world!');

, , , , .

0

Source: https://habr.com/ru/post/1787109/


All Articles