重写包含Typescript类中的闭包的javascript

时间:2018-08-23 01:48:35

标签: typescript

如何在typescript类中的javascript下面重写。 原型中的greet2函数是立即调用函数。

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 个答案:

答案 0 :(得分:1)

您可以声明该属性,然后在原型上对其进行初始化:

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();

实施this suggestion后,您将可以使用真正的静态初始化程序。

答案 1 :(得分:0)

  

如何在打字稿类中的javascript下面重写

使用属性初始值设定项:

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);