[确定不进来?]this,call,apply的作用与区别

在我们学习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;

有不同的见解可以留言讨论!!!

                                                                                                                           

                                                                                         

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值