在我们学习js的过程中,在this这个地方通常会产生迷糊,下面就让我们来了解一下this的使用吧.
this是一个关键字,正常情况下,用于赋值对象
在不同的程序中,赋值的对象也不同
//看this 代码在哪里写的
//----->全局 this===window
//---->函数 看第二步
//1.是什么函数?
//2.----->如果是function函数
//3.看函数是谁触发的?
//-----> call bind apply this===三个函数的实参一
//new this===new 创建的对象
//---事件函数 this===触发事件的dom元素
//---普通对象触达 this===普通对象
1.在全局作用域下,this指向的是window

2.在构造函数中,this指向的是调用构造函数中的实例对象;如下图
this指向的是Animal{}

3.在对象函数中调用,哪个函数调用对象函数,this就指向那里,
如下图,this.a指向的是全局中的a,并不是obj中的,因为obj中没有a,所以输出undefined,this.b在obj中存在所以输出指向的222
window.a=111;
let obj={
b:222,
fn:function(){
console.log(this.a);//undefined
console.log(this.b);//222
}
}
obj.fn();
4.call和apply :
call和apply都是改变this的指向,借用别人的函数来实现自己的功能
区别:call传的是行参的个数,apply传的是形参的arguments数组
call:
function Person(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
}
function Student(name,sex,age,tel,grade){
Person.call(this,name,sex,age);//把Person中的对象给借过来让自己使用; (this)很重要 不要忘记啦!!!
this.tel=tel;
this.grade=grade;
}
var student=new Student('lk','男','23','110','111');
console.log(student);
apply
function Wheel(wheelSize,style){
this.wheelSize=wheelSize;
this.style=style;
}
function Sit(c,sitColor){
this.c=c;
this.sitColor=sitColor
}
function Model(height,width,len){
this.height=height;
this.width=width;
this.len=len;
}
function Car(wheelSize,style,c,sitColor,height,width,len){
Wheel.apply(this,[wheelSize,style])
Sit.apply(this,[c,sitColor])
Model.apply(this,[height,width,len])
}
var car=new Car(200,'玛莎','真皮','pink',300,100,4900);
console.log(car)
//call 需要把实参按照形参的个数传进去
//apply 需要传一个arguments;
有不同的见解可以留言讨论!!!
本文深入解析JavaScript中的this关键字,详细介绍了其在不同上下文中的指向变化:全局作用域、构造函数、对象方法及通过call、apply调用的情况,并通过实例说明了如何利用call和apply改变this指向。

被折叠的 条评论
为什么被折叠?



