玩笑过后

导航

关于this对象

1、在全局函数中this指的是window

2、当函数被当做方法调用时,this等于那个对象

3、匿名函数具有全局性,只要是匿名函数,this指向window

实例1:

var name = 'the window';
    var obj = {
        name:'the obj',
        getName:function(){
            return function(){
                return this.name
            }
        }
    };

    console.log(obj.getName()());//the window

由于最后返回的是匿名函数,所以this指向为window,结果为the window

实例2:

var name = 'the window';
    var obj = {
        name:'the obj',
        getName:function(){
            var _this = this;
            return function(){
                return _this.name
            }
        }
    };

    console.log(obj.getName()());

我们可以借助闭包,声明一个变量_this,把当前的对象付给_this,然后调用_this上边的属性

posted on 2018-07-10 16:03  玩笑过后  阅读(114)  评论(0编辑  收藏  举报