1.函数
(1)自执行函数
函数的定义和执行同时进行
语法:
(function(){
console.log('执行代码')
})()
(2)arguments函数内置参数
函数中内置的存储实参值的对象,是个伪数组。
function sum(){
var s=0
for(var i=0;i<arguments.length;i++){
var item=arguments[i]
s+=item
}
console.log('和为:',s)
}
sum(10,23,45,66)
2.this关键字
每个函数内部都有一个关键字this,可直接使用。他表示当前对象,跟他具体的使用场景有关。
(1)普通函数
//1.普通函数 this => window
function fn(){
console.log('普通函数的this指向:',this)
}
fn()
(2)定时器
//2.定时器 this => window
setTimeout(function(){
console.log('定时器this指向:',this)
},100)
(3)自执行(调用)函数
//3.自执行(调用)函数 this => window
(function(){
console.log('自执行函数this指向:',this)
})()
(4)对象方法
//4.对象方法 this => 方法调用者 (obj)
var obj={
name:'rose',
say:function(){
console.log('对象方法this指向:',this)
}
}
obj.say()
(5)事件处理函数
<div style="width: 100px;height: 100px;background-color: cadetblue;"></div>
<script>
//5.事件处理函数 this => 事件源 (div)
var divEle=document.querySelector('div')
divEle.addEventListener('click',function(){
console.log('事件处理函数this指向:',this)
})
</script>
3.改变this指向
- call:函数名.call(要指向的对象,原参数1,...)
- apply:函数名.apply(要指向的对象,[原参数1,...])
- bind:返回改变了this指向的新函数,调用新函数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>改变this指向</title>
<!--
三种方法:call,apply,bind
-->
</head>
<body>
<script>
var jack={
name:'jack',
age:23,
battery:20,
charge:function(batteryNum){
this.battery=batteryNum
}
}
var rose={
name:'rose',
age:23,
battery:50
}
//给jack充电
console.log('jack充电前的电量:',jack.battery)
jack.charge(100)
console.log('jack充电后的电量:',jack.battery)
//给rose充电
console.log('rose充电前的电量:',rose.battery)
//jack.charge.call(rose,90) //call 方法
// jack.charge.apply(rose,[80]) //apply 方法
var newFn=jack.charge.bind(rose) //bind 方法
newFn(70)
console.log('rose充电后的电量:',rose.battery)
</script>
</body>
</html>