简体   繁体   中英

Javascript Function Self Invoking Inside Object

Instead using setInterval i can use this, to repeatly call an function.

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

The problem is, i want to do the same thing, inside an object , here the snippet.

var evt;
var init;

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

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

Then the error shows up, it said

this.cycle() is not a function.

I'm trying to make an variable as this at the above line of my codes, here, like 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");

But still getting.

parent.cycle() is not a function

Is there a way to do this, what i want here is, went i call evt.cycle("Hello World") after first attempt showing Hello World it will repeatly showing Hello World in every next seconds.

I need to keep the function inside the object that generated by that function. Thanks for any correction.

When you return a new object a new scope is defined. So you should bind this pointer to the function. Or you can use .bind(this) function in this way:

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

For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Or you can use call or apply: 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

In es6 you could use ()=>{} (arrow) function, when the this pointer is inherited.

Other working solution:

 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/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"); 

I extended the example a little bit to illustrate the effect of this a little more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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