简体   繁体   中英

Function not showing correct result

I have written this code

var foo = {
    x:2,
    baz: {
        x:1,
        bar:function() {
            return this.x;
        }
    }
}

var go = foo.baz.bar;
console.log(go());

The answer is undefined. But why? When go maps to the function bar , it should return 2 because we have x:2 in foo .

To answer the question, as Tushar said in the comments:

this context depends on how the function is being called

Here's a snippet to illustrate some ways to achieve what you want, using bind , call or apply

 var foo ={ x:2, baz: { x:1, bar:function() { return this.x; } } }; var go = foo.baz.bar; console.log("go(): " + go()); //this === window, window.x is undefined console.log("go.bind(foo)(): " +go.bind(foo)()); //this === foo, foo.x is 2 console.log("go.bind(foo.baz)(): " +go.bind(foo.baz)()); //this === foo.baz, foo.baz.x is 1 console.log("go.apply(foo): " + go.apply(foo)); //2 console.log("go.apply(foo.baz): " + go.apply(foo.baz)); //1 console.log("go.call(foo): " + go.call(foo)); //2 console.log("go.call(foo.baz): " + go.call(foo.baz)); //1 var x = 100; console.log(go()); //100, since window.x == 100 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM