js中的this
在刚学习js的时候,使用js中的this时,总会感觉非常的迷惑,有时指的是当前的对象,有的时候又是window,而且在前段js和node中全局的挂载对象也不相同,有时候就弄得迷迷糊糊的,所以今天就详细了解一下this并写下学习笔记加深印象。
tihs指向调用该方法的对象
1.首先我们要知道每一个函数都有一个this指向当前对象,当没有指定当前对象的时候默认是由全局对象进行调用的所以当在最外层调用一个没有挂载对象的函数时指向的是全局对象,在浏览器中指向的是window,在ndoe中则是一个Object [global]来调用;
function pepole(){
console.log(this);
this.sec=function(){
console.log(this);
}
}
pepole()//object[global]
p=new pepole();//pepole {}
//在申明了一个新对象之后
在自学的实验过程中,我发现,我明明在pepole的方法中给了一个方法是sec;
但在声明新对象的时候并没有打印出我声明的那个方法,于是我在p中调用sec方法进行尝试
p.sec();//pepole { sec: [Function] }
得到如上结果我就猜测在创建新对象的时候。依次执行语句在前面个的console.log()发生时并没有挂载这个方法。但这时我也产生了疑惑,为什么上面的this和函数里的this指向的是一个对象,思考之后可以这样理解:
this.sec将function挂载到当前的对象之上,这样调用sec的也就是新创建的对象我就想那么无限大的这样在方法中挂载新的方法this应该都是指向最外层的调用第一个函数的对象;实验结果如下
//执行函数
function pepole(){
console.log(this);
this.sec=function(){
console.log(this);
this.tre=function()
{
console.log(this)
this.four=function(){
console.log(this)
}
}
}
}
//打印出的结果
pepole {}
pepole { sec: [Function] }
pepole { sec: [Function], tre: [Function] }
pepole { sec: [Function], tre: [Function], four: [Function] }
可以使用call()和apply()改变调用当前函数的对象
function testcall(){
this.str="转换后的对象";
this.con=function(){
console.log(this.str)
}
}
function test(){
this.str="转换前的对象";
this.con=function(){
console.log(this.str)
}
}
let after=new test();
let before=new testcall();
after.con(); //转换前的对象
after.con.call(before); //转换后的对象
es6箭头函数中this
在es6箭头函数出来之前,this指向的是当前调用函数的对象,这就导致了使用的时候定义不明确,导致有时候无法调用到定义时想用的函数。 在箭头函数下的this则表示的是定义时所指向的对象
// setTimeout(function(){
// console.log(this)
// },300)
function testafter(){
this.name="转换后的对象";
}
function test(){
this.name="转换前的对象";
this.ca=()=>{
console.log(this.name)
}
}
let tes=new test();
tes.ca.call(tes1) //小明
let tes1=new testafter();
tes.ca.call(tes1)//小明
与上面的call函数例子相反,这次并没有应为改变了调用对象而使得this所指向的对象发生了改变
回调函数中的this
最后我要说下在一种特殊情况下的this,那就是在回掉函数下this总是指向最外层的全局对象,在阅览器端指向的是window,在node上是objec[global].
//function test(){
// this.callback=function(call){
// call()
// }
//} //使用es6箭头函数this依然是指向全局对象
function test(){
this.callback=(call)=>{
call()
}
}
let a=new test();
a.callback(function(){
console.log(this) //object[global]
})
在实验时想是不是用箭头函数会不一样,但通过上面的实验表明了回调函数使用箭头函数依然指向全局对象