【发布时间】: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