手贱,写个call玩玩.

今天在睡觉醒时,突然感觉对call和apply有了点理解,但是又不好表达出来.就随便写几个例子.

 1         function say() {
 2             return this.role;
 3         }
 4         function Father() {
 5             this.role = "爸爸";
 6         }
 7         function Mother() {
 8             this.role = "妈妈";
 9         }
10         function Brother() {
11             this.role = "兄弟";
12         }
13         alert(say.call(new Father()));//爸爸
14         alert(say.call(new Mother()));//妈妈
15         alert(say.call(new Brother()));//兄弟
16         alert(say.call(null)); //undefind
17         alert(say.call(window)); //undefind

call形式:say.call(obj,args);

理解:正常执行say()方法,say()方法中的this指向obj实例.args是传入到say()中的参数,不过这里没有用.

原文地址:https://www.cnblogs.com/guoyansi19900907/p/3584873.html