this浅谈

    /*this最终指向的是调用它的对象,这里的函数a实际是被Window对象所点出来的  */

    function wan() {

        var userName = '十五'

        console.log(this.userName, '十五') //undefined

        console.log(this, '十五') //window

    }

    wan()

    /*this指向的是对象w,因为你调用这个fn是通过w.fn()执行的,那自然指向就是对象w,这里再次强调一点,this的指向在函数创建的时候是决定不了的,在调用的时候才能决定,谁调用的就指向谁  */

    var w={

         userName : '十五',

         fn:function(){

          console.log(this.userName, '十五') //十五 

          console.log(this) //w

         }

    }

    w.fn()

    //* 这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象 */

    var w = {

    a:10,

    b:{

        a:12,

        fn:function(){

            console.log(this.a,'十五'); //12

            console.log(this,'十五');//b

        }

    }

}

w.b.fn();

你可能感兴趣的:(this浅谈)