函数定义方式
function fun(){
console.log('声明式')
}
var fun=function(){
console.log('赋值式')
}
(function(){
console.log('我是自执行函数')
})()
arguments函数所有实参的集合
function getMax() {
var max = arguments[0]
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i]
}
}
return max
}
console.log(getMax(1, 43, 43, 2525, 52));
改变this指向谁调用函数this指向的就是谁
- call
函数名.call(this指向的对象是谁,参数逗号隔开)
var jackObj = {
name: 'jack',
dl: 30,
cdb: function (num) {
this.dl = num
}
}
var roseObj = {
name: 'rose',
dl: 10
}
console.log('rose以前的电量', roseObj.dl);
jackObj.cdb.call(roseObj, 100)
console.log('rose充电后的电量', roseObj.dl);
- apply
函数名.apply(this指向的对象是谁,[参数1,参数2])
var jackObj = {
name: 'jack',
dl: 30,
cdb: function (num) {
this.dl = num
}
}
var roseObj = {
name: 'rose',
dl: 10
}
console.log('rose以前的电量', roseObj.dl);
jackObj.cdb.apply(roseObj, [100])
console.log('rose充电后的电量', roseObj.dl);
- bind
函数名.var newFun=bind(this指向的对象是谁),bind不会对源方法操作会返回一个新方法,参数放在返回的新方法
var jackObj = {
name: 'jack',
dl: 30,
cdb: function (num) {
this.dl = num
}
}
var roseObj = {
name: 'rose',
dl: 10
}
console.log('rose以前的电量', roseObj.dl);
var newObj= jackObj.cdb.bind(roseObj)
newObj(100)
console.log('rose充电后的电量', roseObj.dl);