今天在睡觉醒时,突然感觉对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()中的参数,不过这里没有用.

相关文章:

  • 2021-05-25
  • 2022-03-02
  • 2021-10-21
  • 2022-02-28
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-03-08
猜你喜欢
  • 2021-09-20
  • 2021-11-29
  • 2022-03-08
  • 2021-12-26
  • 2021-12-04
  • 2021-10-22
相关资源
相似解决方案