Hey, I am about to rewrite开发者_如何学JAVA 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.
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;
})();
Yes it is possible, but why would you do that? To make JavaScript look like the few other languages (like VB and Delphi) that don't need the parentheses (brackets are those square thingies) for functions? The creators of JavaScript have decided that a function should be called with parentheses, regardless of the amount of parameters. You are actually making properties that refer to function results just to skip two characters.
I think what you are actually looking for, is a class or object. You could write this:
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);
}
Now, you can instantiate this class and call methods:
var c = new MyClass;
c.anyMethod2('Hello world!');
This is only a small example, but you should really read about declaring and using classes, because I think that might be what you're looking for.
精彩评论