首页 > 其他 > 详细

this的指向总结

时间:2019-06-17 09:27:49      阅读:130      评论:0      收藏:0      [点我收藏+]
    // this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象.
    // 根据函数调用的方式不同,this会指向不同的对象,跟创建方式没有关系.


    // 1、以函数的形式调用时。this指向的是window
    function fun() {
        console.log(this.name)
    }
    // fun();



    // 2、以方法的形式调用时,this就是调用方法的那个对象
    var obj={
        name:"小明",
        aa:fun
    };

     // obj.aa();



    // 3、如果不在第一层调用,那么this只会指向当前层
    var a={
        b:5,
        c:{
            b: 10,
            d:function () {
                console.log(this.b)
            }
        }
    };

    // a.c.d()



    // 4、如果将这个方法赋值给变量时,this会改变对象的指向

    var n={
        name:"狗子",
        firstname:function () {
           console.log(this.name)
        }
    };

    var x={
        name:"笨蛋"
    };

    x.firstname=n.firstname;
    // x.firstname()
    n.firstname()



    // 5、在构造函数中,this的指向实例化的对象


    var person=function () {
        this.name="蔡徐坤"
    };

    var cxk=new person ();
    // console.log(cxk.name)

 

this的指向总结

原文:https://www.cnblogs.com/dumenglong/p/11037767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!