首页 > 技术文章 > this 作用域

lcw5945 2014-12-04 14:57 原文

this 通常是指当前实例对象,每个函数在被调用时,会自动创建2个特殊变量,this和arguments ,他们只活动在函数内部,不会访问外部。

var name = "glob this";

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

document.writeln(obj.getName()());
// glob this

输出结果:glob this

匿名函数中this访问的是全局对象

var objs={
    name : "obj this",
    getName : function(){
        var that = this;
        return function(){
            return that.name;
        }
    }

}

document.writeln(objs.getName()());

输出结果:obj this

如果想让闭包匿名函数访问当前域下的name 必须将当前域this保存临时变量中,然后在匿名函数中使用这个临时变量。

 

this 指针是上下文环境的属性,不是某个变量的属性,this不能被赋值,它和进入上下文相关

function foo(){console.log(this);}
foo(); //window
foo.prototype.constructor(); //foo
new foo(); // foo

  

推荐阅读