JS Set the function of the Timer call class itself from the interior of the class

xiaoxiao2021-03-06  18

JS Set the function of the Timer call class itself from the interior of the class

Question: (JavaScript) You need to use SetInterVal inside the class to set up a timer access to this class itself.

Analysis: Inside the class, you can use this to access itself, however, the parameters behind this setInterval are the function name string, that is, to setInterval ("SomeFunction", delay). Although this Timer is set inside the class, it is the same for this function. It is now necessary to see it as the externally calling this function. And if it is in the external call, it is nothing to do with the general: setInterval ("SomeObject.someFunction ()", delay). But the problem is here, we don't know the SomeObject this string in the class, this is what we have after the object is created. Var someobject = new someclass ()

Method 1: Start thinking, if there is a mechanism to get an instance object name, you can get an external object name internally. But the truth is impossible (I think). The stupid approach is to pass this object name like class, such as initialization: Var homeObject = New SomeClass ("SomeObject"). Then I will write this objectid = "someobject" when SomeClass () initialize, then setInterval (ObjectID ". SomeFunction ()", delay) is OK.

Method 2: The above method is feasible, but this is obvious that it feels uncomfortable, don't twist! Where is the way to pass the name to the name! So just think about it. After careful consideration, it is thought to set an external unique object ID inside (not an external statement of the external declaration), and then point this ID to the object itself (this). This is done! Specifically, this is:

this.id = this.generateID // Generate a random string to do ID, such as generating an "obj_xxx" Eval (this.id "= this"); // This Eval is equivalent to OBJ_XXX (this is External variables) = this (object itself)

That is to say, a variable points to yourself. If the outside declares a homeObject = new someclass, then this obj_xxx point to SomeObject, so you don't have to know someObject, because we know Obj_xxx! !

转载请注明原文地址:https://www.9cbs.com/read-50083.html

New Post(0)