理解上下文和作用域

上下文和作用域不同

scope is function-based while context is object-based 作用域是基于方法的,上下文基于对象

What is "this" Context 什么是"this"上下文

当方法是作为一个对象的函数被调用的时候,this就会指向这个对象:

var obj = {
    foo: function() {
        return this;   
    }
};

obj.foo() === obj; // true

使用new关键字创建对象的时候,this就会指向这个新创建的实例:

function foo() {
    alert(this);
}

foo() // window
new foo() // foo

Execution Context 执行期上下文

The Scope Chain 作用域链

对于每个执行期上下文,都有一个作用域链与它相关联:

function first() {
    second();
    function second() {
        third();
        function third() {
            fourth();
            function fourth() {
                // do something
            }
        }
    }
}
first();

Understanding Scope and Context in JavaScript

results matching ""

    No results matching ""