- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- <script>
- // 第一个用途: 函数上下文模式改变 this 的指向
- var age = 19;
- function fun() {
- console.log(this.age);
- }
- var obj = {
- age: 26
- };
- fun.apply(obj);
- fun.call(obj)
- // 总结: apply 和 call, 第一个参数功能都是一样, 都是可以改变 this 指向为第一个参数对象
- // 当传递对象为 null 的时候, 为 window 调用
- // 应用 1: 将参数用 - 拼接
- function fun2() {
- //arguments 是一个伪装数组, 不能调用 join 方法, 通过 apply 转换替代对象来调用
- console.log(Array.prototype.join.apply(arguments, ["-"]));
- console.log(Array.prototype.join.call(arguments, "-"));
- }
- fun2(1, 2, 3, 4);
- // 应用 4: 借用构造函数实现继承
- function Persion() {
- this.name = "张三";
- this.age = 18;
- }
- function Student() {
- Persion.apply(this);
- }
- var stu = new Student();
- console.log(stu);
- // 第二个用途: 第二个到第 N 个参数的处理
- function fun1(name, work) {
- console.log("名字为" + name + "; 年龄为" + this.age + "职业" + work);
- }
- var obj1 = {
- age: 30
- };
- /*
- * apply 和 call 第二个参数都是函数的参数
- * apply 是传递的数组, 执行的时候是将数组遍历然后作为参数传递
- * call 传递的是分开的参数
- * */
- fun1.apply(obj1, ["张三", "金融"]);
- fun1.call(obj1, "张三", "金融");
- // 应用 2:apply 的遍历
- window.onload = function() {
- var divs = document.querySelectorAll("div");
- var spans = document.querySelectorAll("span");
- var arr = [];
- arr.push.apply(arr, divs);
- arr.push.apply(arr, spans);
- for (var i = 0; i < arr.length; i++) {
- arr[i].style.backgroundColor = "red";
- }
- }
- // 应用 3: 求最大值
- var arr1 = [3, 6, 1, 78, 23];
- console.log(Math.max.apply(null, arr1));
- </script>
- <style>
- div,span{ display: inline-block; width: 50px; height: 50px; border: 1px
- solid pink; }
- </style>
- </head>
- <body>
- <div>
- </div>
- <div>
- </div>
- <div>
- </div>
- <div>
- </div>
- <br>
- <span>
- </span>
- <span>
- </span>
- <span>
- </span>
- <span>
- </span>
- </body>
- </html>
来源: http://www.bubuko.com/infodetail-2492740.html