0

This is proper Typescript (or ES6 if you ignore the static typing):

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter("world");

console.log( greeter.greet() ); //Hello world

But the following creates Hello undefined, how would you rewrite this in a way it would work? And, if that's not possible, what would be the alternative to achieve this?

I'm looking into passing variables directly to functions.

class Greeter {
    greet(greeting: string) {
        return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter();

console.log( greeter.greet("world") ); //Hello undefined

UPDATE:

I'm referring to PHP like class usage like:

class Greeter {
    public function greet($greeting){
        return $greeting;
    }
}
Bob van Luijt
  • 7,153
  • 12
  • 58
  • 101
  • Why would you expect `this.greeting` to hold the value passed as a parameter to `greet`? –  Sep 12 '15 at 11:12
  • possible duplicate of [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/questions/13418669/javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) – Bergi Sep 12 '15 at 11:16
  • `greeting` is a variable (declared as a named parameter), not a property of the instance. No difference in ES5, btw. – Bergi Sep 12 '15 at 11:17
  • @Bergi thanks for this link, my question is a bit different, updated the question. – Bob van Luijt Sep 12 '15 at 11:35
  • @torazaburo based on: http://goo.gl/k3uFXe – Bob van Luijt Sep 12 '15 at 11:36
  • @Bergi not sure what you mean, how would that be different as a variable passed to the function directly...? – Bob van Luijt Sep 12 '15 at 11:37
  • @bvl: No, I don't think it's much different (or at least my answer there should clear up your confusion). You cannot access variables or parameters of functions with a `this.` prefix in JavaScript - that is only for object properties. Use `greeting` instead of `this.greeting` and it'll work. – Bergi Sep 12 '15 at 11:37

1 Answers1

3

You can pass variable into object to store while doing a call. And you may use it afterwards like below without passing a variable. And then you can change it with another call.

class Greeter {
    greet(greeting: string) {
      this.greeting = greeting || this.greeting;
      return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter();

console.log( greeter.greet("world") ); //Hello world
console.log( greeter.greet() ); //Hello world
console.log( greeter.greet("es6") ); //Hello es6
Erhan
  • 1,126
  • 8
  • 11