1

how to rewrite below javascript in typescript class. The greet2 function in prototype is an immediately invoke function.

function Greeter(greeting) {
    this.greeting = greeting;
}

Greeter.prototype.greet = function() {
    return "Hello, " + this.greeting;
}

//an immediately invoke function
Greeter.prototype.greet2 = function{
    let blabla = 'hello, ';
    return function greet2(foo) {
        return blabla + foo;
    }
}();

let greeter = new Greeter({message: "world"});  

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet2('tom'));
};

document.body.appendChild(button);

2 Answers 2

1

You can declare the property and then initialize it on the prototype:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
    greet2!: (foo) => string;  // in case of strictPropertyInitialization
    static staticInitializer() {
        // Here we have access to non-public members of `Greeter`.
        Greeter.prototype.greet2 = function(){
            let blabla = 'hello, ';
            return function greet2(this: Greeter, foo) {
                return blabla + foo;
            }
        }();
    }
}
Greeter.staticInitializer();

When this suggestion is implemented, you'll be able to use a real static initializer.

Sign up to request clarification or add additional context in comments.

Comments

0

how to rewrite below javascript in typescript class

Using a property initializer:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
    greet2 = (() => {                      // HERE 
        let blabla = 'hello, ';
        return function greet2(foo) {
            return blabla + foo;
        }
    })()
}

let greeter = new Greeter("world");

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
}

document.body.appendChild(button);

1 Comment

This is less efficient than the original: it's evaluated once for each object instantiated instead of once when the class is defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.