//上下文模式:根据用户传递的参数产生不同的结果 //实现方式:call/apply:这两个都是定义在Function.prototype.call——>目的:任何函数都可以访问到call/apply //call方法的第一个参数表示(本次调用该函数,)函数内部的this的值 function fn(){ console.log(this.name);//张三 } fn();//函数调用模式——>this指向window window自带一个name属性:"" fn.call({name:"张三"}); var o={}; fn.call(o);//本次调用,fn函数内部的this的值指向o对象 //——>打印结果:undefined(一个对象中访问不到某个属性的时候,值就是undefined) function foo(){ console.log(this.name); return [1,3,5]; } foo();//函数调用模式——>foo函数内部的this指向window,返回值由return决定 //window.name——>"" var f1=foo.call({name:"张三"});//上下文调用模式——>foo函数内部this指向传递的参数 //this.name——>"张三" console.log(f1.__proto__);//返回值由return语句决定 //——>Array.prototype var f2=new foo();//构造函数调用模式——>foo函数内部this指向构造函数的实例 //——>this.name:undefined console.log(f2.__proto__);//——>Array.prototype function fn(){ for (var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } } //利用call方法来调用fn函数的时候,如果需要传递实参,将实参作为call方法的的第二个参数开始依次传递 fn.call(null,1,3,5);//call方法的第二个参数是fn方法的第一个实参,第三个参数是fn方法的第二个实参 fn.apply(null,[1,3,5]);//apply方法的第二个参数是一个数组对象,这个数组中第一个元素是fn的第一个实参,数组的第二个元素是fn的第二个实参。。。 //fn.apply(函数内部的this的值,[实参1,实参2。。。实参n]) //面试题:call/apply方法有什么异同? //1、相同点:a、他们都是Function.prototype对象中定义的方法 // b、第一个参数都是表示函数内部的this的值 //2、不同点:如果需要给函数传递参数的时候,利用call方法,将函数的参数从第二个参数开始依次排开 // 利用apply方法,apply方法的第二个参数是一个数组对象,数组的第一个参数表示函数的第一个实参,依次以此类推 //数组里面的push方法实现的功能:往数组里面添加一个元素 var arr=[1,3,5];//{0:1,1:3,2:5,length:3} arr.push(10);//{0:1,1:3,2:5,3:10,length:4} //伪数组 var o={0:10,length:1}; // o[1]=20; // o.length++; // o[2]=30; // o.length++; // o[3]=50; // o.length++; //借用数组的push方法:首先需要访问到push方法 //使用场景1、借用数组的push方法往伪数组里面添加元素 [].push.call(o,10,30,50,70,80,100); [].push.apply(o,[10,30,50,70,80,100]); //使用场景2:借用数组的push方法往数组中添加多个元素(这多个元素在一个数组中) var arr1=[1,3,5]; var arr2=[10,20,30]; //要将arr2中的元素依次添加到arr1中 // for (var i = 0; i < arr2.length; i++) { // arr1.push(arr2[i]); // } //[].push.call(arr1,arr2);//——>往arr1中添加一个元素,该元素是一个数组 [].push.apply(arr1,arr2);//——>往arr1中添加了多个元素 //——>push方法内部通过隐式迭代的方式添加多个元素 /借用构造函数实现继承:需要2个构造函数 function Person(name,age){ this.name=name; this.age=age; } // function Student(name,age,number){ // this.name=name; // this.age=age; // this.number=number; // } function Student(name,age,number){ //借用构造函数实现继承 Person.call(this,name,age); this.number=number; } var s1=new Student("张三",20,666); //借用构造函数实现继承:子类构造函数(Student)借用父类构造函数(Person)来完成:给子类的实例添加属性 //注意条件:由于要借用父类构造函数,所以父类构造函数的功能要对子类对象通用