简体   繁体   English

该对象未传递给对象方法

[英]this object not getting passed to object method

I have a JavaScript code snippet which is as following: 我有一个JavaScript代码段,如下所示:

 var obj = { message: "Hello", innerMessage: !(function() { console.log(this.message); })() }; console.log(obj.innerMessage); 

It outputs: undefined true 输出: undefined true

The function which gets executed for evaluating innerMessage property prints the message property of the object on which the method is called. 为评估innerMessage属性而执行的函数将打印调用该方法的对象的message属性。 The value of that property is Hello . 该属性的值为Hello However what gets printed is undefined . 但是,打印出的内容是undefined It looks like the object is not getting passed to the method. 看起来对象没有传递给方法。 Why is it happening? 为什么会这样呢?

It outputs: undefined true 输出:undefined true

undefined is due to console.log statement in IIFE undefined是由于IIFE中的console.log语句

(function() {
        console.log(this.message);
    })() //prints undefined and returns `undefined`

And true is because innerMessage is a boolean as you negated !undefined ==> true . true是因为您否定了innerMessageboolean !undefined ==> true

    var obj = {
      message: "Hello",
      innerMessage: !(function() {
      })()
    };
    obj.innerMessage = function(){
     alert(this.message);
    }

obj.innerMessage();

If you want to get the message, You can use this.message after you created object you need to make function decleration. 如果要获取消息,则可以在创建对象后使用this.message进行函数清理。

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

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