javascript this详解

   当调用函数使用了new关键字时,此时this指代一个新的上下文,不再是全局的。

   

<script type="text/javascript">
foo = "bar";

function testThis() {
this.foo = "foo";
}

console.log(this.foo); //logs "bar"
new testThis();
console.log(this.foo); //logs "bar"

console.log(new testThis().foo); //logs "foo"
</script>

在函数嵌套时,内层函数通过闭包获取外层函数的变量值,而不是通过this继承。

function Thing() {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
var info = "attempting to log this.foo:";
function doIt() {
console.log(info, this.foo);
}
doIt();
}


var thing = new Thing();
thing.logFoo(); //"attempting to log this.foo: undefined"

上述 doIt方法中的this指代全局变量 window。!!?