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()
)将是另一个函数。但从你的评论来看,我的假设似乎是错误的。我要回去测试我的假设(;我花了很长时间才理解你第一次修复的第二部分,但现在它已经用魔法完美修复了,不要碰评论,谢谢(;