简体   繁体   English

JavaScript 匿名 Function 带有来自 Call() 的参数

[英]JavaScript Anonymous Function With Parameters From Call()

I am trying to do the following:我正在尝试执行以下操作:

function main(callback) {
   $.ajax('server-side', function() {
       this.callback.call("hello");
   }.bind({ callback: callback });
}

main(function(response) {
   alert(response);
});

Response is undefined , I would expect it to be "hello" . Response is undefined ,我希望它是"hello" Any ideas why?任何想法为什么?

call first argument should be a reference to "this". call第一个参数应该是对“this”的引用。 Being "this" the context where you want to execute your function. Call function Mozila MDN作为“这个”你想要执行你的 function 的上下文。 调用 function Mozila MDN

You wrote:你写了:

function main(callback) {
   $.ajax('server-side', function() {
       this.callback.call("hello");
   }.bind({ callback: callback });
}

main(function(response) {
   print response;
});

print doesnt exists in javascript. print 不存在于 javascript 中。

then you wrote this.callback.call, which is wrong然后你写了this.callback.call,这是错误的

you should write你应该写

callback.call(this,"hello") , 

just check the call function signature.只需检查呼叫 function 签名即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM