【问题标题】:Same name for function and method, cannot call the former within the latter函数和方法同名,不能在后者中调用前者
【发布时间】:2014-06-10 22:04:03
【问题描述】:

我正在尝试为函数和方法(对象的函数)使用相同的方法名称,并从方法内部调用该函数。但是,该函数根本不会被调用。这些是函数的相关位:

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)
  }

以及方法

的相关位
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;
  }

应该在发送表单时从这个脚本调用:

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

它成功调用了该方法并显示了两条消息。但是,函数中的Sending 不会被记录,也不会执行任何请求。我正在考虑范围或函数名称被覆盖的问题,但我不是这里的专家,因此将不胜感激。 为什么没有调用函数 post()?控制台中绝对没有显示错误。

经过一些测试,我可以确认问题在于他们共享名称。那么,我如何才能为一个方法和一个函数共享相同的名称呢? 方法只能像 u("form").post(callA, callB); 那样被调用,而函数像 post(url, data, callA, callB)l; 那样被调用

【问题讨论】:

  • 您有任何错误吗?像堆栈溢出一样?
  • 您希望this 在您的u 函数的主体中是什么?提示:如果您要执行类似obj.u("form").post(...) 的操作,那么u 主体内的this 将是obj,如果您只是在执行u("form").post(...),那么this 将是全局对象并分配给@ 987654335@ 将覆盖现有功能。也许你应该在某个地方有new
  • 我希望它在u 的范围内,所以u.post() 将是一个函数,而post()(或window.post())将是一个不同的函数。但从你的评论看来,我的假设是错误的。我要回去测试我的假设(;

标签: javascript scope naming


【解决方案1】:

问题在于您对u 函数的调用。您忘记了 new 关键字,它使 this context 成为全局范围对象 - 然后您将在其上覆盖全局 post 变量。

两个修复:

  • 使用(new u("form")).post(…); 或使您的构造函数new-agnostic
  • 不要将post 函数放在全局范围内。使用模块模式。

【讨论】:

  • 我花了很长时间才理解您的第一个修复的第二部分,但现在它已通过 magic, do not touch 评论完美修复,谢谢 (;
猜你喜欢
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多