繁体   English   中英

Javascript函数自调用内部对象

[英]Javascript Function Self Invoking Inside Object

代替使用setInterval,我可以使用它来重复调用一个函数。

function foo(){
    setTimeout(foo, 1000);
}();

问题是,我想在一个object (这里是片段)中做同样的事情。

var evt;
var init;

evt = function() {
    return {
        cycle:function(str) {
            setTimeout(function(str) {
                this.cycle(str);
            }, 1000);
        }
    }
}

init = new evt();
init.cycle("Hallo word");

然后出现错误,它说

this.cycle()不是函数。

我正在上面的代码行中尝试像this创建一个变量,就像这样

var evt;
var init;

evt = function() {
    var parent;

    parent = this;
    return {
        cycle:function(str) {
            setTimeout(function(str) {
                parent.cycle(str);
            }, 1000);
        }
    }
}

init = new evt();
init.cycle("Hallo word");

但仍然得到。

parent.cycle()不是函数

有没有一种方法可以做到,我想要的是,在第一次尝试显示Hello World之后我打电话给evt.cycle("Hello World") ,它将在接下来的每秒钟重复显示一次Hello World

我需要将函数保留在该函数生成的对象内。 感谢您的任何更正。

当您返回新对象时,将定义新范围。 因此,您应该将此指针绑定到函数。 或者,您可以通过以下方式使用.bind(this)函数:

setTimeout((function(str){ 
}).bind(this), 1000)

有关更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

或者您可以使用call或申请: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

在es6中,当this指针被继承时,可以使用()=> {}(箭头)函数。

其他工作解决方案:

 var evt; var init; evt = function() { var parent; parent = this; return { cycle:function(str) { var me = this; setTimeout(function(str) { console.log("cycle"); me.cycle(str); }, 1000); } } } init = new evt(); init.cycle("Hallo word"); 

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

 const evt = function() { return { i: 0, cycle: function(str) { const _this = this; setTimeout(() => { console.log(str.substring(0, this.i)); _this.cycle(str, ++this.i); }, 1000); } } } init = new evt(); init.cycle("Hello world"); 

我延长了示例一点点地示出的效果this一点更。

暂无
暂无

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

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