gpt4 book ai didi

javascript - 如何在 'data' 中设置像 "jQuery.ajax({ success : function(data)"这样的回调函数参数?

转载 作者:行者123 更新时间:2023-12-03 23:59:11 25 4
gpt4 key购买 nike

我想知道如何将回调函数的第一个参数设置为我想要的,就像 jquery 在成功回调或完成回调中所做的一样

我想这样做:

$.ajax({
success: function(data) {
alert(data)
}
});

据我所知,这是我能达到的最接近我想要的

function test(text) {
this.text = text
this.success = function(this.text) { }
}

var a = new test('King Kong')
a.success = function(k){
alert(k)
}

我想让警报说“金刚”

最佳答案

这是一个在构造函数中接受回调然后稍后调用它以响应某个触发器的示例。在下面,触发器是调用 trigger 函数的人,但它可以是任何你想要的:

function Test(text, callback) {

this.text = text;
this.success = callback;
}

Test.prototype.trigger = function() {
// Call the success callback, passing in the text
this.success(this.text);
};

var a = new Test('King Kong', function(k) {
alert(k);
});

a.trigger();

(我在此处设置了 Test initially-capped。这是构造函数的约定,您当然可以随意忽略它。)

要理解的关键、基本的事情是,函数就像其他任何东西一样只是对象。您可以传递对它们的引用等。要调用一个函数,您只需访问存储函数引用的任何变量并添加括号(可选地在括号中加上函数的参数)。

因此,以下所有调用 foo 函数并触发警报:

function foo(msg) {
alert(msg);
}

var f = foo; // No parens, just getting the function reference, not calling it
f("Hi there"); // Now we're calling it
var a = {};
a.nifty = f;
a.nifty("Hi again");

function bar(func) {
func("Hello for the third time");
}
bar(foo); // Passing a reference to `foo` into the `bar` function, which will call it

高级:现在,jQuery 做的一件事是调用回调,并将 this 值设置为特定的值(通常是与调用相关的 DOM 元素) .每当您通过对象属性调用函数时,都会发生这种情况:

var a = {name: "Fred"};
a.func = function() {
alert(this.name);
};
a.func(); // alerts "Fred"

...但这不是您可以做到的唯一方法;函数对象本身还有 callapply 函数:

var a = {name: "Fred"};
function func() {
alert(this.name);
}
func.call(a); // alerts "Fred"

函数没有分配给 a 的任何属性,但是我们使用 call 调用了函数,它接受 的值>this 作为它的第一个参数。 Call 还会将任何其他参数传递给您正在调用的函数:

function func(msg1, msg2) {
alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.call(a, "one", "two"); // alerts "Fred says one and two"

apply 做完全相同的事情,但它接受参数作为数组而不是离散参数传递给底层函数:

function func(msg1, msg2) {
alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.apply(a, ["one", "two"]); // alerts "Fred says one and two"
// ^------------^----- note these args are now an array

更多阅读:Mythical Methods

关于javascript - 如何在 'data' 中设置像 "jQuery.ajax({ success : function(data)"这样的回调函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4492932/

25 4 0