skip to Main Content

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


  1. Is possible to do that?

    No. If you do not have access to localFunc, you can’t change something that’s hardcoded into myObj.myFunc‘s call to localFunc (in this example, the property name used when creating the object to pass to it). You’d have to replace myObj.myFunc, and to do that, you’d have to have access to localFunc.

    Login or Signup to reply.
  2. 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:

    • Rename the method name: if the same method name is creating some
      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.
    • Use static methods. This approach is kind of similar if compared
      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().
    • Create a common interface: you can create a single method called
      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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search