this

严格模式,函数禁止this指向window,下面函数中代码this 为 undefined

'use strict';

var a = function(){
    console.log(this); //undefined
}

a()

for(var i = 0 ;i < 1;i++)
{
    console.log(this); //window
}
f()

this 对象实在运行的时候基于函数的执行环境绑定的,当函数被作为某个对象的方法调用时,this等于那个对象。 匿名函数执行环境具有全局性,this通常指向window

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function() {
        console.log(1,this.name);
    },
    getNameFunc2: function() {
        return function(){
            return function(){
                console.log(2,this.name);
            }
        }
    },
    getNameFunc3: function(a) {
        var foo =  function(a){
            console.log(3,this.name);
        }
        return foo;
    }

};

var o2 = function(){
    this.name = 'o2';   //this === window
    object.getNameFunc();//My Object
    object.getNameFunc3()(); //  o2
}
o2()

object.getNameFunc();   //My Object
object.getNameFunc2()()(); // "The Window"
object.getNameFunc3()();//"The Window"

你可能感兴趣的:(this)