简体   繁体   English

在方法中访问javascript对象的属性

[英]Accessing javascript object's properties in the method

For the below code snippet i am expecting the answer as "number" but i am getting it as "undefined". 对于以下代码段,我期望答案为“数字”,但我将其作为“未定义”。 Can anyone please help me here to find out why its returning "undefined" ? 任何人都可以在这里帮助我,找出其返回“未定义”的原因吗?

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

(function () {
    return typeof arguments[0](); //this will return "undefined"
})(foo.bar);

If i do typeof foo.bar(), then it will give me the expected answer as "number". 如果我键入foo.bar(),那么它将给我预期的答案为“数字”。

Thanks in advance. 提前致谢。

That's because this with normal functions is set by how the function is called , not where it's defined. 这是因为this与正常的功能是由该函数的调用 ,而不是在那里它被定义设置。 (ECMAScript2015's "arrow" functions are different, they inherit this from where they're created, not how they're called.) (ECMAScript2015的“箭头”功能有所不同,它们从创建位置继承this功能,而不是从调用方式继承。)

You have a couple of options: 您有两种选择:

1) Use Function#bind to create a new function that, when called, will call your original function with the correct this : 1)使用Function#bind创建一个新函数,该新函数在被调用时将以正确的this调用原始函数:

 var foo = { bar: function() { return this.baz; }, baz: 1 }; (function() { snippet.log(typeof arguments[0]()); })(foo.bar.bind(foo)); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

2) Use your own wrapper function: 2)使用您自己的包装函数:

 var foo = { bar: function() { return this.baz; }, baz: 1 }; (function() { snippet.log(typeof arguments[0]()); })(function() { return foo.bar.apply(foo, arguments); }); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

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

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