Francisco Presencia
Francisco Presencia

Reputation: 8851

Same name for function and method, cannot call the former within the latter

I'm trying to use the same method name for both a function and a method (a function of an object) and calling the function from inside the method. However, the function does not get called at all. These are the relevant bits of the function:

function post(url, data, success, error) {

  console.log("Sending");      // This doesn't get even called

  var request = new XMLHttpRequest();      // Nor a request is made

  // ... (more code here)
  }

And the relevant bits of the method

function u(parameter) {

  // ... more code here

  this.post = function(success, error) {     // post request

    this.on("submit", function(e) {     // Loop through all the nodes

      e.preventDefault();     // Stop the browser from sending a request

      console.log("Going to send your data");     // This works

      post(u(this).attr("action"), u(this).serialize(), success, error);     // Post the actual data

      console.log("Got here");     // Well it's async, but it also gets here
      });

    return this;
    }

  return this;
  }

It is supposed to be called from this script when the form is sent:

u("form").post(function(){
  alert("Yay, it worked");
  }, function(){
  alert("Something went wrong");
  });

It successfully calls the method and both of the messages are shown. However, the Sending from the function is NOT logged and no request is performed. I'm thinking either a problem with scope or with the function name being overwritten, but I'm not an expert here so any help would be appreciated. Why is the function post() not being called?. There's absolutely no error shown in the console.

After some testing, I can confirm the problem is that they share the name. So, how could I have the same name shared for a method and a function? The method would only be called like u("form").post(callA, callB); and the function like post(url, data, callA, callB)l;

Upvotes: 0

Views: 50

Answers (1)

Bergi
Bergi

Reputation: 664464

It's your call of the u function that is problematic. You forgot the new keyword, which made the this context be the global scope object - on which you then are overwriting the global post variable.

Two fixes:

  • Use (new u("form")).post(…); or make your constructor new-agnostic
  • Don't put the post function in the global scope. Use the module pattern.

Upvotes: 1

Related Questions