JavaScript 21 函数的调用

来源:互联网 发布:c语言编程软件win10 编辑:程序博客网 时间:2024/06/10 15:44
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#d1{
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="d1"></div>
<!--在行间绑定js事件时 函数名后加()-->
<button onclick="alert(11)">按钮</button>
<script type="text/javascript">
/*
* 函数内的代码调用时才会执行

*/
/*
* 函数执行:
* 1.通过事件触发来执行函数
*   通过绑定事件的处理函数,不需要加()就可以执行
* 2.函数名()
*   函数名后只要添加小括号 该函数就会立刻执行
*/
document.getElementById("d1").onclick=function(){
this.style.background="red";
};
//函数名可以作为一个变量用于赋值
document.getElementById("d1").onmouseover=change;
function change(){
this.style.background="orange";
};


</script>
<script type="text/javascript">
//计时器中关联的事件函数写法:
//1.
setInterval(function(){
console.log(1)

},1000);
//2.直接给函数名作为参数
// setInterval(move,1000);
//3.函数名后加()的话,要加引号
setInterval("move()",1000);
var i=0;
function move(){
i++
document.getElementById("d1").style.transform="translateX("+i*100+"px)";
if(i>6){
i=0;
}
}
/*3种调用方式:
* 函数名()
* call()
* apply()
*/
function sum(x,y){
//this:在函数中代表调用当前函数的调用者,若没有明确的调用者,则代表window
console.log(this);
return x+y;
}
/*函数调用的方式:
* 方式1:函数名(参数1,...参数2,....)
*/

var res=sum(3,5)
//alert(res);8
//方式2:函数名.call(this指向的对象,参数1,...参数2,...)
var res1=  sum. call(document.body,3,5);
console.log(res1)
//方式3:函数名.apply(this指向的对象,数组,)
//数组内存放实参
  var res2= sum.apply(this,[4,5])
//alert(res2);


</script>
</body>
</html>
原创粉丝点击