Javascript中的call和apply让人觉得很神奇和好玩.有了它俩,js的面向对象编程方便了一大截.
下面通过两个例子来理解call和apply.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function egg() {}
egg.prototype = { egg_type: '未知动物', hatch: function(legs){ if (!legs) { legs = 0; } console.log('孵化出一只 ' + this.egg_type + ',有 ' + legs + ' 条腿'); } }
tmp_egg = new egg(); tmp_egg.hatch();
duck_egg = { egg_type: '小鸭子' }; tmp_egg.hatch.call(duck_egg,2);
crocodile_egg = { egg_type: '小鳄鱼'}; tmp_egg.hatch.apply(crocodile_egg,[4]);
|
多重继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function animal(){ this.name = function (name) { console.log('我是 ' + name); } }
function cry(sound){ this.sound = function(sound){ console.log('我的叫声 ' + sound); } }
function fowl() { animal.call(this); cry.apply(this); }
tmp_chicken = new fowl(); tmp_chicken.name('鸡'); tmp_chicken.sound('咕咕咕');
tmp_duck = new fowl(); tmp_duck.name('鸭'); tmp_duck.sound('嘎嘎嘎');
|
总结:
call和apply功能相同,都是用来改变函数体内部 this 指向的.
call和apply的区别是,apply的第二个参数是个数组.