浅析 JavaScript 中的 apply 和 call 用法的差异
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Apply And Call</title> 5 <script type="text/javascript"> 6 window.onload = function () { 7 function water() { 8 this.color = "blue"; 9 this.drink = function (txt) { 10 txt = txt || ""; 11 console.log("drink the " + this.color + " wateer" + txt); 12 } 13 } 14 15 function apple() { 16 this.color = "red"; 17 this.show = function (txt) { 18 txt = txt || ""; 19 console.log("the apple color is " + this.color + txt); 20 } 21 } 22 23 function add(a, b) { 24 return a + b; 25 } 26 27 //参数传递差别 28 var num1 = add.call(this, 1, 2); 29 var num2 = add.apply(this, [1, 2]); 30 console.log(num1); 31 console.log(num2); 32 33 34 var w = new water(); 35 w.drink(); //输出 drink the blue wateer 36 var a = new apple(); //输出 the apple color is red 37 a.show(); 38 //执行环境差别 call 39 w.drink.call(a, " 测试文本1"); //输出 drink the red wateer 测试文本1 40 41 a.show.call(w, " 测试文本2"); //输出 the apple color is blue 测试文本2 42 43 //执行环境差别 apply 44 w.drink.apply(a, [" 测试文本1"]); //输出 drink the red wateer 测试文本1 45 46 a.show.apply(w, [" 测试文本2"]); //输出 the apple color is blue 测试文本2 47 48 } 49 </script> 50 </head> 51 <body> 52 </body> 53 </html>