代码之家  ›  专栏  ›  技术社区  ›  Irvan Hilmi

javascript函数在对象内部自调用

  •  0
  • Irvan Hilmi  · 技术社区  · 7 年前

    相反,使用SETTIFECT,我可以使用这个函数,重复调用函数。

    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()不是函数

    有办法吗,我要的是,我打电话过去 evt.cycle("Hello World") 首次试镜后 Hello World 它将重复显示 你好世界 在接下来的每一秒。

    我需要将函数保存在由该函数生成的对象中。谢谢你的指正。

    0 回复  |  直到 7 年前
        1
  •  1
  •   tdev    7 年前

    当您返回一个新对象时,将定义一个新的作用域。所以您应该将这个指针绑定到函数。或者你可以用这种方式使用.Boin(this)函数:

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

    更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

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

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

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

    其他工作方案:

    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");
        2
  •  1
  •   manonthemat    7 年前

    https://developer.mozilla.org/en-US/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 再多一点。