Home >Web Front-end >JS Tutorial >Transferring objects in the window.setTimeout method_javascript tips

Transferring objects in the window.setTimeout method_javascript tips

WBOY
WBOYOriginal
2016-05-16 19:23:07917browse

The syntax is:

window.setTimeout(expr,msec)

expr is the execution string, and after msec milliseconds, it will be run as js. I just discovered yesterday that expr can also be a function. Haha, using this feature, objects can be transferred.
The following code implements the function of delayed transmission of object p in function foo1 to function foo2.


[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh to execute
]


[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh To execute
][Ctrl A Select all Note:
If you need to introduce external Js needs to be refreshed to execute
]

Many frameworks now actually directly use a multi-cast event (its implementation principle is not complicated). A multi-cast event itself is actually a standard function. But it generally has the following methods.

MuEvent.add = function (func) { ... }

MuEvent.addMethod = function (instance, func) { ... }



When using the first method, when activating the func event processing function, use the current instance of MuEvent as this object; the second method uses the incoming instance as this object.



So for setTimeout, our traditional method is to use it to activate the method like this:

----------
function doTimer() {
obj1.call();
obj2.call();
}
setTimeout(doTimer, 1000);


and use multi-cast events The code can be as follows:

----------
var e = new MuEvent();
e.addMethod(obj1, obj1.call);
e.addMethod(obj2, obj2.call);

setTimeout(e, 1000);
----------



Of course , if you want to write more COOL, you can do it like this:

----------

setTimeout(function() {

return new MuEvent (obj1, obj1.call, obj2, obj2.call);

}(), 1000); <script> foo1() function foo1(){ var p={x:3,y:4} window.setTimeout(function(){foo2(p)},100) } function foo2(p){ alert(p.x) } </script>---------- <script> foo1() function foo1(){ var p={x:3,y:4} window.setTimeout(function(){foo2(p)},100) } function foo2(p){ alert(p.y) //输出foo1的p={x:3,y:4} 的y } </script><script> var pp=3; foo1() function foo1(){ var p={x:3,y:4} var pp=1; window.setTimeout(function(){foo2('pp')},100) window.setTimeout("(function(){foo2("+pp+")})()",200) //也就是说,这个函数其实将参数值传过去.相当于如下将foo2引用进来运行: window.setTimeout("(function(){alert("+pp+")})()",200) } function foo2(pp){ alert(pp) var pp=2; alert(pp) } </script>As a little introduction , the Qomo I made is MuEvent implemented in this form. Most frameworks like Atlas adopt a similar approach.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn