javaweb开发-js代码中的function.call的参数

<script type="text/javascript">
window.color = "透明";
var testObj = { color: "红色" };

function testFuc() {
alert(this.color);
}

$(function () {
1.testFuc(); //弹出“透明”
2.testFuc(this); //弹出“undefined”
3.testFuc.call(this.parent); //弹出“透明”
4.testFuc.call(window); //弹出“透明”
5.testFuc.call(testObj); //弹出“红色”
});
</script>
复制代码
上面这段代码演示了call的作用。第一个函数调用,this指向了window,所以弹出了window的color属性。

第二个函数可能有些朋友以为也会弹出透明,但是请先确定我们的函数运行在$(function(){});中,这个jQuery的函数,了解jQuery的朋友都很清楚,在

$(function(){});中this的作用域指向的是document,然后我们调用testFunc,要弹出document的color,当然是未定义的。

第三个函数将testFunc的this指向了document的亲爹window,弹出window的color当然也是没有问题的。

第四个函数就更加直白了,把window传进去了

第五个函数,将testFunc的this指向了testObj,弹出了红色。

posted @ 2015-12-21 17:26  老冯9  阅读(409)  评论(0编辑  收藏  举报