JavaScript 中 this 是如何工作的 ?

this 永远指向函数运行时所在的对象,而不是函数创建时所在的对象

  1. 匿名函数和不处于任何对象中的函数,This指向window
  2. call, apply, with指的This是谁就是谁。
  3. 普通函数调用,函数被谁调用,This就指向谁

this 永远指向函数运行时所在的对象,而不是函数创建时所在的对象

var obj = {
    x: 10,
    fn: function() {
        console.log(this);
        console.log(this.x);
    }
}
var fn1 = obj.fn;
obj.fn()
// Object {x: 10, fn: function}
// 10
fn1()
// window
//undefined

匿名函数和不处于任何对象中的函数,This指向window

var obj = {
    x: 10;
    fn: function () {
        function f() {
            console.log(this);
            console.log(this.x);
        }
        f();
    }
}
var fn = function () {
    console.log(this);
    console.log(this.x);
}
function Foo() {
    console.log(this);
    console.log(this.x);
}
obj.fn()
// window
// undefined
fn()
// window
// undefined
Foo()
// window
// undefined

results for ""

    No results matching ""