回調函數是什么在學習之前還真不知道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 + "
主站蜘蛛池模板:
房山区|
革吉县|
双桥区|
河西区|
抚松县|
谢通门县|
班玛县|
和平区|
博爱县|
柘城县|
交城县|
南通市|
洪雅县|
贞丰县|
泸水县|
淄博市|
新巴尔虎右旗|
柞水县|
奉新县|
靖州|
正安县|
磐安县|
巴南区|
改则县|
江川县|
盐亭县|
闻喜县|
衡阳县|
陆川县|
临澧县|
鹤岗市|
讷河市|
思南县|
尚义县|
深圳市|
兴仁县|
永平县|
色达县|
佛学|
昌宁县|
延边|