call 和 apply的使用
call
/** * 改变this指向 * */ function People(){ this.name = "--"; this.age = 0; this.show = function(){ console.log(this.name,'今年',this.age,"岁"); } } function Man(name, age){ this.name = name; this.age = age; } var people = new People(); var man = new Man("小明",25); people.show(); // -- 今年 0 岁 people.show.call(man); //小明 今年 25 岁
/** * 继承 * */ function People(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Man(name,song){ //继承 People this.song = song; People.call(this,name); } // 自己的特长(原型方法) Man.prototype.sing = function(){ console.log("爱唱",this.song); } var man = new Man("朱元璋","光辉岁月"); man.showName(); //朱元璋 man.sing();// 爱唱 光辉岁月
apply
/** * 改变this指向 * */ function People(){ this.name = "--"; this.age = 0; this.show = function(){ console.log(this.name,'今年',this.age,"岁"); } } function Man(name, age){ this.name = name; this.age = age; } var people = new People(); var man = new Man("小明",25); people.show(); // -- 今年 0 岁 people.show.apply(man); //小明 今年 25 岁
/** * 继承 * */ function People(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Man(name,song){ //继承 People this.song = song; People.apply(this,[name]);//注意区别 } // 自己的特长(原型方法) Man.prototype.sing = function(){ console.log("爱唱",this.song); } var man = new Man("朱元璋","光辉岁月"); man.showName(); //朱元璋 man.sing();// 爱唱 光辉岁月
两者之间的却别
1、call是多个参数,apply是两个参数(第二个参数数组的方式传递)
a.call(b,arg1,arg2…) apply(b,[arg1,arg2]) //apply只有2个参数,它将call的参数(arg1,arg2…)放在一个数组中作为apply的第二参数
2、对一些对象方法的调用,比如数组的forEach的调用
call的方法
[].forEach.call('1,2,3',function(item){console.log(item)}); // 1,2,3
apply同样使用会报错
[].forEach.call('1,2,3',function(item){console.log(item)}); // VM777:1 Uncaught TypeError: undefined is not a function(…)