How to get the instance name of an object

后端 未结 7 1325
萌比男神i
萌比男神i 2021-01-15 00:07

I use the below code to write code to query a web method in a specified interval.

now in the this.Poll function I have to do

this.tmo = setTimeo         


        
相关标签:
7条回答
  • 2021-01-15 00:30

    You can use this handy little wrapper to execute a function periodically at given interval (1 sec by default):

    function tick(func, interval) {
        return (function() {
            if(func())
                setTimeout(arguments.callee, interval || 1000);
        })();
    }
    

    The function is repeated until it returns false:

    tick(function() {
       if(should stop) return false;
       do stuff
       return true;
    });
    

    If the function is a method, make a closure as shown

    // inside your object
    var me = this;
    tick(function() {
       return me.doStuff();
    });
    
    0 讨论(0)
  • 2021-01-15 00:31

    Loose the parenthesis in this.Poll(). You call this function right away, not after a time interval. If you loose the brackets, it will pass a function, not a result of it, to setInterval and you won't have any issues.

    setTimeout(this.Poll, this.Interval);
    

    Otherwise you call the function right away and nothing holds this pointer anymore, and IE just deletes it.

    In fixed variant, this.Poll will hold pointer to this and it won't be deleted.

    0 讨论(0)
  • 2021-01-15 00:37

    I just wanted to say, this self trick has saved me a ton of hair pulling.

    I didn't think to create a reference like this. It means dynamically-created elements with on click events can call the correct instance of my class.

    0 讨论(0)
  • 2021-01-15 00:38

    I've asked another question, the answer is here:

    JavaScript: List global variables in IE

    Iterating through the global variables and check whether it equals "this".

    0 讨论(0)
  • 2021-01-15 00:41

    You could also use:

    i.e.

    var name = findInstanceOf(cPoll);
    
    function findInstanceOf(obj) {
        for (var v in window) {
            try {
                if (window[v] instanceof obj)
                    return v;
            } catch(e) { }
        };
        return false;
    }
    

    From http://www.liam-galvin.co.uk/2010/11/24/javascript-find-instance-name-of-an-object/#read

    0 讨论(0)
  • 2021-01-15 00:43

    I provided an answer for a similar question today in which I created a polling class from scratch. You may want to adopt it for yourself. In the sake of not duplicating, here's a link a link to said question:

    Poll the Server with Ajax and Dojo *

    * Despite the title, my solution offers both "vanilla" and Dojo styles.

    0 讨论(0)
提交回复
热议问题