Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数和方法的名称相同,不能在后者中调用前者_Javascript_Scope_Naming - Fatal编程技术网

Javascript 函数和方法的名称相同,不能在后者中调用前者

Javascript 函数和方法的名称相同,不能在后者中调用前者,javascript,scope,naming,Javascript,Scope,Naming,我尝试对函数和方法(对象的函数)使用相同的方法名,并从方法内部调用函数。但是,该函数根本不会被调用。这些是函数的相关位: function post(url, data, success, error) { console.log("Sending"); // This doesn't get even called var request = new XMLHttpRequest(); // Nor a request is made // ... (mo

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

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");
  });
它成功地调用了该方法,并显示了这两条消息。但是,不会记录来自功能的
发送
,也不会执行任何请求。我想要么是作用域有问题,要么是函数名被覆盖有问题,但我不是这里的专家,所以任何帮助都将不胜感激。为什么没有调用函数post()?。控制台中绝对没有显示错误


经过一些测试后,我可以确认问题在于他们共享名称。那么,我怎么能让一个方法和一个函数共享相同的名称呢?这个方法只能像
u(“form”).post(callA,callB)那样调用
和类似
post(url,data,callA,callB)l的函数

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

两个修正:

  • 使用
    (新u(“表格”)).post(…)或创建构造函数
  • 不要将
    post
    函数放在全局范围内。使用模块模式

您是否发现任何错误?像堆栈溢出一样?您希望
函数的
u
函数体中会出现什么
this
?提示:如果您要执行类似于
obj.u(“form”).post(…)
的操作,则
u
主体内部将是
obj
,如果您只是执行
u(“form”).post(…)
将是全局对象,并分配给
此.post
将覆盖现有函数。也许你应该在那里的某个地方有
new
?我希望它在
u
的范围内,因此
u.post()
将是一个函数,
post()
(或
window.post()
)将是另一个函数。但从你的评论来看,我的假设似乎是错误的。我要回去测试我的假设(;我花了很长时间才理解你第一次修复的第二部分,但现在它已经用魔法完美修复了,不要碰评论,谢谢(;