简体   繁体   中英

this object not getting passed to object method

I have a JavaScript code snippet which is as following:

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

It outputs: undefined true

The function which gets executed for evaluating innerMessage property prints the message property of the object on which the method is called. The value of that property is Hello . However what gets printed is undefined . It looks like the object is not getting passed to the method. Why is it happening?

It outputs: undefined true

undefined is due to console.log statement in IIFE

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

And true is because innerMessage is a boolean as you negated !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.

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