简体   繁体   中英

TypeScript Arrow function as return in another function in class return problem

look at this code. When i look at console i have something like this:

() => {
            return this.msg;
        }

To be honest its wired for me. One more thing. When i change return this.msg for console.log(this.msg) nothing happend in console. What ma i doing wrong?

class Problemo {
  msg: string = "hello"

  printFunction() {
    var vv = () => {
      return this.msg
    }

    return vv
  }
}

var pp = new Problemo()
var xx = pp.printFunction()

console.log(xx)

@Solution. i forgot about brackets console.log(xx())

Your printFunction method declares a function vv that will print this.msg when called, so the value of pp.printFunction() will be a function, which you assign to xx and log to the console. That's why you see the source of the function:

console.log(xx) // outputs: () => { return this.msg; }

If you call xx instead, you will see the message:

console.log(xx()) // outputs: "hello"

TypeScript playground

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