简体   繁体   English

功能未显示正确的结果

[英]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 . go映射到功能bar ,它应该返回2因为foox:2

To answer the question, as Tushar said in the comments: 正如Tushar在评论中所说,要回答这个问题:

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 这是一个片段,说明使用bindcallapply实现您想要的内容的一些方法

 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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