Zero, Comma and parentheses - A Javascript Trick
When I was digging into the source code of React Antd, this line took my notice. Actually, later I found this trick is heavily used through the whole project.
exports.default = function(obj, key, value) {
if (key in obj) {
// what the hell is this line doing?
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
The line with comment may seems interesting, it can be simplified as:
(0, obj.method)(targetObject, param1, ...)
Sure it’s a method call, but why need the parenthesis, zero and the comma 🤔
It’s all about Reference Type - read this carefully. Reference type is an internal merchanism that js runtime leverages when dealing with function call. I will illustrate with examples (thanks for the beautiful codesandbox):
So, things are clear here: the zero is nothing but a “placeholder”, it exists just to ensure the parenthesis will grab off the reference type of object method. The whole trick is a claim says:
“Though I might look like a method bound to an object, but I don’t use ‘this’ at all, please treat me like a util method.”
You could write obj.method.call(...)
instead, but use comma and parenthesis is more semantically clear. Last, hope tc39 will include my propoal: &obj.method(target, parm1...)
😂