Suppose this code in some JavaScript file:
const localFunc = function(v) { if(v.b) console.log(v.b) else console.log('wrong!'); }
var myObj = {
myFunc: function(v) { localFunc({a:v}); }
}
Suppose we have access to myObj
but not to localFunc
.
We want to execute localFunc({b:v})
instead of localFunc({a:v})
;
Is possible to do that?
2
Answers
No. If you do not have access to
localFunc
, you can’t change something that’s hardcoded intomyObj.myFunc
‘s call tolocalFunc
(in this example, the property name used when creating the object to pass to it). You’d have to replacemyObj.myFunc
, and to do that, you’d have to have access tolocalFunc
.First idea which come to mine was Overloading , which JavaScript Does not support.
Long Story Short , no you can’t do this using javaScript.
The alternative to overload
Some alternatives:
confusion, try to rename the methods to create a meaningful name
better than createDocument, like: createLicenseDriveDocument,
createDocumentWithOptionalFields, etc. Of course, this can lead you
to giant method names, so this is not a solution for all cases.
to the first alternative above. You can use a meaningful names to
each case and instantiate the document from a static method on
Document, like: Document.createLicenseDriveDocument().
createDocument(InterfaceDocument interfaceDocument) and create
different implementations for InterfaceDocument. Per example:
createDocument(new DocumentMinPagesCount("name")). Of course you
don’t need a single implementation for each case, because you can
create more than one constructor on each implementation, grouping
some fields that makes sense on that implementation. This pattern is
called telescoping constructors.
Source: https://softwareengineering.stackexchange.com/questions/235096/how-to-avoid-excessive-method-overloading