回調函數是什么在學習之前還真不知道js回調函數怎么使用及作用了,下面本文章把我在學習回調函數例子給各位同學介紹一下吧,有需了解的同學不防進入參考。
回調函數原理:
我現在出發,到了通知你”
這是一個異步的流程,“我出發”這個過程中(函數執行),“你”可以去做任何事,“到了”(函數執行完畢)“通知你”(回調)進行之后的流程
例子
1.基本方法
<script language="javascript" type="text/javascript">function doSomething(callback) {// … // Call the callbackcallback('stuff', 'goes', 'here');} function foo(a, b, c) {// I'm the callbackalert(a + " " + b + " " + c);} doSomething(foo); </script>或者用匿名函數的形式
<script language="javascript" type="text/javascript"> function dosomething(damsg, callback){ alert(damsg); if(typeof callback == "function") callback(); } dosomething("回調函數", function(){ alert("和 jQuery 的 callbacks 形式一樣!"); }); </script>
2.高級方法
使用javascript的call方法
<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.call(this);} function foo() {alert(this.name);} var t = new Thing('Joe');t.doSomething(foo); // Alerts "Joe" via `foo`</script>
傳參數
<script language="javascript" type="text/javascript"> function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback, salutation) {// Call our callback, but using our own instance as the contextcallback.call(this, salutation);} function foo(salutation) {alert(salutation + " " + this.name);} var t = new Thing('Joe');t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`</script>使用 javascript 的 apply 傳參數
<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.apply(this, ['Hi', 3, 2, 1]);} function foo(salutation, three, two, one) {alert(salutation + " " + this.name + "
主站蜘蛛池模板:
昆明市|
绩溪县|
临桂县|
玛多县|
伊宁县|
塔河县|
古丈县|
蕉岭县|
手游|
焦作市|
荆州市|
巫山县|
恩平市|
阿克陶县|
康马县|
灌阳县|
克什克腾旗|
潞西市|
沙坪坝区|
江西省|
阿图什市|
康乐县|
灵石县|
利川市|
车险|
和硕县|
瑞昌市|
东平县|
山阳县|
临洮县|
岫岩|
城步|
靖安县|
化德县|
涪陵区|
读书|
漳州市|
綦江县|
漳州市|
青阳县|
寿光市|