gpt4 book ai didi

javascript - 如何在javascript匿名函数中调用类slibing函数

转载 作者:行者123 更新时间:2023-11-30 08:49:42 26 4
gpt4 key购买 nike

我试图通过以下方式在匿名函数中访问对象的成员函数-

  function a()
{
this.memb = 10;
}

a.prototype.hide_member = function(id){
alert(id);
}

a.prototype.show_member = function(){
setTimeout('this.hide_member(this.memb)', 2000); //Problem 1
setTimeout(this.hide_member(this.memb), 2000); //Problem 2
setTimeout(alert(this.memb), 2000); //Problem 3
this.memb++;
}

var obj = new a();
obj.show_member();

在这里,问题 1 - 是代码在给定的正确时间执行,意味着刚好在 2000 毫秒之后,但它在 2000 毫秒之后显示以下错误 -

Uncaught TypeError: Object [object global] has no method 'hide_member'
(anonymous function)

问题 2 - 代码正在执行,但它在代码解析后立即执行,意味着不是在 2000 毫秒之后。

问题 3 - 与问题 2 相同的问题

我在这里对这 3 个问题感到困惑。谢谢

最佳答案

这里发生了几件事:

在这段代码中:

setTimeout(this.hide_member(this.memb), 2000);

您正在立即调用 this.hide_member,并将其返回值传递给setTimeout。这与 foo(bar()) 完全一样,您在其中调用 bar 并将其返回值传递给 foo.

您需要将一个函数传递给setTimeout,然后从该函数中调用成员函数。请注意,在函数内,this 会有所不同,因此您必须记住它:

a.prototype.show_member = function(){
var self = this,
memb_to_hide = this.memb;
setTimeout(function() {
self.hide_member(memb_to_hide);
}, 2000);
this.memb++;
}

请注意,我还记得要在函数中使用的 this.memb 的旧值。

另一种方法是使用 ES5's Function#bind ,但它要求浏览器的 JavaScript 引擎具有该功能(或者您已经加载了“ES5 垫片”,因为 bind 是一个可垫片功能):

a.prototype.show_member = function(){
setTimeout(this.hide_member.bind(this, this.memb), 2000);
this.memb++;
}

Function#bind 返回一个函数,该函数在被调用时将使用您在第一个参数中作为 this 提供的值调用原始函数(然后传递任何进一步论证)。在这种情况下,我们没有必须记住 this.memb 的旧值,因为我们已经将旧值传递给 bind .


旁注:您依赖于自动分号插入的恐怖。我建议不要这样做,并在语句末尾提供分号,例如:

a.prototype.mumble = function() {
/*...*/
}; // <=== Note the ;

关于javascript - 如何在javascript匿名函数中调用类slibing函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com