Home  >  Q&A  >  body text

javascript - Pointing issues about this

var foo = "window";
var obj = {
    foo : "obj",
    getFoo : function(){
        return function(){
            return this.foo;
        };
    }
};
var f = obj.getFoo();
console.log(f());  //结果:window

Why is the result of the above code running window?

天蓬老师天蓬老师2670 days ago776

reply all(5)I'll reply

  • 滿天的星座

    滿天的星座2017-06-28 09:27:33

    obj.getFoo() returns an equation assigned to f .
    f is called via f() without an explicit caller, so this is just window .

    If you want to get "obj", you can do this

    var foo = "window";
    var obj = {
        foo : "obj",
        getFoo : function(){
            var self = this;
            return function(){
                return self.foo;
            };
        }
    };
    
    var f = obj.getFoo();
    console.log(f());

    reply
    0
  • 阿神

    阿神2017-06-28 09:27:33

    Because, where f() actually runs, this is window. Since the context is not changed through call or bind, the output is window.

    You can replace it as follows:

    console.log(f());
    // ----->
    console.log(obj.getFoo());
    // ----->
    console.log(function() {
        var self = this;
        return function() {
            return self.foo
        }
    });

    The self here points to window, so return self.foo is return window.foo, which is 'window'.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-28 09:27:33

    In fact, the simplest understanding is that obj.getFoo gives f, and then look at where this method runs.

    f = function () {
        return function () {
            return this.foo
        }
    }

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-28 09:27:33

    f() in console.log(f()) is called independently
    1. If the caller function is owned by an object, then when the function is called, the internal this points to the object.
    2. If the function is called independently, then this inside the function points to undefined.
    Recommended reading http://www.jianshu.com/p/d647... I hope it will be helpful to you

    reply
    0
  • PHP中文网

    PHP中文网2017-06-28 09:27:33

    Function execution, this in the function body points to the caller of the function

    1. In the following code, the caller of the getFoo function is obj, so this inside the getFoo function points to the obj object

    var f = obj.getFoo()

    2. The getFoo function returns an anonymous function and assigns it to the variable f, and then executes the function f. At this time, the variable f is mounted on the window. The caller of the function f is the window, and this inside the function f also points to the window

    console.log(f());  //结果:window

    reply
    0
  • Cancelreply