码迷,mamicode.com
首页 > 移动开发 > 详细

call和apply方法

时间:2017-11-07 19:48:12      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:nal   height   apply()   www   1.0   public   ansi   xhtml 1.0   控制   

普通函数中是否也有this关键字,this指向谁呢?

<script type="text/javascript">
     function myfun(){
        console.log(this);
     }
     myfun();
</script>

技术分享

控制函数内部的this指向:

函数都可以打点调用call()apply()方法,可以帮我们制定函数内部的this指向,在函数调用过程使用这两个方法。

 

var oDiv = document.getElementsByTagName(‘div‘);
function fun(){
   console.log(this);
}
//fun.call(oDiv);
fun.apply(oDiv);

 

作用:

 1、执行fun函数

2、在fun函数内部指定this的指向oDiv

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style type="text/css">
div{
width: 200px;
height: 200px;
background: red;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<script type="text/javascript">
/*function fun(){
console.log(this);
}
fun();*/
var oDiv = document.getElementsByTagName(‘div‘)[0];
/* function fun(){
console.log(this);
}
//fun.call(oDiv);
fun.apply(oDiv);*/

/*function sum(a,b){
this.style.backgroundColor = "pink";
}
sum.call(oDiv);
sum.apply(oDiv);*/

function sum(a,b){
this.style.backgroundColor = "pink";
console.log(a+b);
}
sum.call(oDiv,2,3);
sum.apply(oDiv,[3,5]);
</script>

 

call和apply 区别:

函数传递参数的语法不同。

sum.call(oDiv,参数1,参数2,参数3...);
sum.apply(oDiv,[参数1,参数2,参数3...])

 

call和apply方法

标签:nal   height   apply()   www   1.0   public   ansi   xhtml 1.0   控制   

原文地址:http://www.cnblogs.com/smivico/p/7800261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!