-
-
Save abozhilov/1333507 to your computer and use it in GitHub Desktop.
function func(a, f) { | |
return function (args) { | |
args.__proto__ = a; | |
f.call(this, args); | |
}; | |
}; | |
var f = func({foo : 10, bar : 20}, function (args) { | |
print(args.foo, args.bar); | |
}); | |
f({}); //10 20 | |
f({foo : 50}); //50 20 | |
f({foo : 50, bar : 50}); //50 50 |
@YmMot your function is OK, but the main drawback is that I have to put that code in the body of function. The idea of my pattern was to keep clean function's body. The main benefit is clever code, especially for the reader. Some people told me that __proto__
is not good for performance. While I agree with that statement, I totally disagree with function like that should be used in performance critical moment. In performance critical moment we usually use optimized functions which haven't default argument values.
Regarding __proto__
, yes it's non-standard mimic of internal [[Prototype]]. Instead of __proto__
you can use Object.create
to create fresh object which inherits from default arguments object and then augment with properties of passed args objects. This would work everywhere. If someone is interested in cross browser solution, I'm able to post it.
The cross browser solution is available: https://gist.github.com/1336141
@ArtS, they are not interchangeable in this instance.
The idea of my pattern was to keep clean function's body.
In both my examples, you're only adding one line of code really. They're also very explicit about what they're doing.
I would argue that your function is less explicit and actually makes things much messier; by either creating a lot of noise at the point of function creation or clouding how the code works by decorating the function later on.
In the case of the former, you're now dealing with anonymous functions which make your stack traces less readable. Decorators are fine in principle, but in this case I just don't see the benefit. Obviously coders should use what they find most readable.
I do think this would be good for partial function application, or for modifying an existing function to take an object of arguments, etc.... I just don't think this should be used for giving functions default arguments and it definitely needs a more descriptive name.
@YmMot , while .proto is not available in all browsers, .prototype should be?