1:函数声明会进行函数提升,也就是函数的预解析
2:函数表达式不会进行函数的提升。则必须在函数后面调用
现在的浏览器不会对函数进行提升。老版本也是会进行函数提升。
则解决函数提升的问题,可以用下面的函数表达式。
var fn;
if(true){
fn=function(){
console.log('fn-true');
}
}else{
fn=function(){
console.log('fn-false');
}
}
fn();
函数内部的this,是由函数调用的时候来确定其指向的
函数的五种形式:
1:普通函数,this指向window
function fn(){
console.log(this);//this指向window
};
fn();
2:方法调用的时候,谁调用this指向谁
var obj={
fn:function(){
console.log(this);//this指向obj
}
};
obj.fn();
3:作为构造函数调用,this指向构造函数创建的对象
4:作为事件处理函数调用,触发该事件的对象。
btn.onclick=function(){
console.log(this);//this指向btn
}
5:作为定时器的参数,定时器的this指向window。
setInterval(function(){
console.log(this);//这里的this指向window
},500);
this指向谁,是由函数调用的时候决定的。
call,bind,apply
1:call,使用call改变伪数组中的this,让其使用数组中的方法push。
var obj={
0:10,
1:20,
2:30,
3:40,
length:4
}
// obj['4']=50;
// obj.length++;
Array.prototype.push.call(obj,50);//实现与上面的方法一致的结果。
console.log(obj);