函数补充
-
自调用函数
函数定义和调用写在一块 (function(){ // 函数体 })()
-
作用:
封装代码
封装私有变量,独立于全局变量 -
arguments 对象
- => 函数所有实参的集合
- => 函数体中直接使用
- => 类数组形式存在
- => 函数可变参数,动态传参
// 计算任意数总和
function sum(){
var s = 0
for(var i = 0; i < arguments.length; i++){
s = s + arguments[i]
}
return s
}
var s = sum(10,20,30,50)
alert(s)
this关键字
this表示当前对象;在同场景下this表示不同的对象
1. 事件处理函数中的this
this->事件源
2. 普通函数中this
this -> window对象
3. 定时器中this
this -> window对象
4. 自调用函数中this
this -> window对象
5. 对象方法中的this 调用该方法的引用变量指向的对象
Object
var obj = {
name:'jack',
say:function(){
console.log( '对象Object方法中this->' ,this); //obj 对象
}
}
obj.say()
<body>
<button>确定</button>
<script>
function test1() {
var btn = document.querySelector('button')
btn.addEventListener('click', function () {
// this->事件源->button按钮
console.log('this : ', this)
})
}
function fun(){
console.log('this -> ',this) //指向window对象
}
fun()
setTimeout(function(){
console.log('定时器 this -> ',this) //指向window对象
},1000)
(function(){
console.log('自调用函数this -> ',this)//指向window对象
})()
var obj = {
name:'jack',
say: function(){
console.log(this.name + '说话, say方法调用'); //jack
console.log('对象Object方法中this -> ',this) //
}
}
obj.say()
</script>
</body>