js中this的指向

例子1

var o = {
            a:10,
            b:{
                // a:12,
                fn:function(){
                    console.log(this.a); //undefined
                }
            }
        }
        o.b.fn();

this只会指向它的上一级对象,不管这个对象中有没有this要的东西

例子2

var a = 20;
        var foo = {
            a: 10,
            getA: function () {
                return this.a;
            }
        }
        console.log(foo.getA()); // 10

        var test = foo.getA;
        console.log(test());  // 20

this永远指向的是最后调用它的对象

 

posted @ 2018-04-18 17:27  xue11hua  阅读(101)  评论(0编辑  收藏  举报