手贱,写个call玩玩.

时间:2023-03-09 18:55:45
手贱,写个call玩玩.

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

         function say() {
return this.role;
}
function Father() {
this.role = "爸爸";
}
function Mother() {
this.role = "妈妈";
}
function Brother() {
this.role = "兄弟";
}
alert(say.call(new Father()));//爸爸
alert(say.call(new Mother()));//妈妈
alert(say.call(new Brother()));//兄弟
alert(say.call(null)); //undefind
alert(say.call(window)); //undefind

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

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