javascript 中 方法call()的理解

来源:互联网 发布:淘宝卖家开不了花呗 编辑:程序博客网 时间:2024/06/05 10:07

<script type="text/javascript">
    var testvar = 'window属性';
    var o1 = { testvar: '1', fun: function () { alert('o1: ' + this.testvar + '<<'); } };
    var o2 = { testvar: '2', fun2: function () { alert('o2: ' + this.testvar); } };
    o1.fun(); 
    o2.fun2(); 
    o1.fun.call(o2);
</script>

 

输出结果为:

o1: 1<<

o2: 2

o1: 2<<

 

一种理解方法

call 方法
调用一个对象的一个方法,以另一个对象替换当前对象。

o1.fun.call(o2);

o1.fun方法中的this指向o2

 

另一各理解方法

o2.fun=o1.fun;
o2.fun();
delete o2.fun;

此时的o2实际被修改为:
var o2 = { testvar: '2', fun: function () { alert('o1: ' + this.testvar + '<<'); } };
但是当两个对象函数名不一样时,这种理解有点问题