this指向
关于this指向,我们可以理解为哪个对象调用函数,函数里面的this指向哪个对象。
function a( ){
console.log(this) ;//this(window)
}
a( );
function b( ) {
console.log(this);//this(b函数对象)
}
new b( );
总结一下就是函数a为普通函数对象,这种函数对象执行的this是window,函数b为构造函数对象,它的this是调用的函数对象
call apply bind的用法
var obj = {
name:'张三',
say:function(str,str2){
console.log(this.name+' '+str+' '+str2) // 李四 hello world
}
}
var f = obj.say.call({name:'李四'},'hello','world');
// call() 可以调用函数,也可以改变函数this的指向
var obj={
name:'张三',
say:function(str,str2){
conlose.log(this.name+' '+str+' 'str2) // 李四 hello world}
}
var f= obj.say.bind({name:'李四'},'hello','world');
f( )
//bind方法使用的时候需要再次调用
var obj={
name:'张三',
say:function(str,str2){
conlose.log(this.name+' '+str+' 'str2) // 李四 hello world
}
}
var f= obj.say.apply({name:'李四'},['hello','world']);
//使用apply方法改变this指向时参数需要以数组形式表达