强制打字稿将方法放在实例上而不是原型上

Fut*_*oad 9 typescript

是否可以强制使用typescript将方法放在实例而不是原型上.我问这个是因为我经常遇到"这个"范围问题,原型上的方法会导致问题.

编辑


例如在ts的输出中似乎不一致,我将FooAlert保留在FooViewModel函数中,但原型中的方法是openFooAlertDialogueAdd

JS

var FooViewModel = (function () {
    function FooViewModel (json) {
        this.Foolert = ko.observable();

    }
    FooViewModel.prototype.openFooAlertDialogueAdd = function () {
        this.FooAlert = something;
    };
Run Code Online (Sandbox Code Playgroud)

TS

class FooViewModel{
     FooAlert = KnockoutObservableAny

      constructor(){
         this.FooAlert = ko.observable();
       }
     openFooAlertDialogueAdd() {
        this.FooAlert = something;
    };

}
Run Code Online (Sandbox Code Playgroud)

tho*_*aux 15

如果你有范围问题,我觉得你儿子不好,我有99个问题,但这不是一个!

史蒂夫的答案显示了定义类方法的正确方法,这些方法将在每个实例上公开.但是,如果您遇到范围问题,这可能是因为您从另一个上下文调用这些方法.

例如,如果您正在使用Knockout并将其中一个方法this绑定到绑定,则Knockout会将范围覆盖到绑定的当前范围,而不是您已定义方法的范围.

有两种方法可以防止这种范围的损失.

首先,您可以在构造函数中定义方法,以在实例上而不是在原型上公开它们.

喜欢:

class Greeter {
    greet:() => string;
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
        this.greet = () => {
            return "Hello, " + this.greeting;
        }
    }
Run Code Online (Sandbox Code Playgroud)

其次,您可以使用click语法来定义类方法.

例:

class Greeter {
    greeting: string;
    constructor() {
        this.greeting: "Blabla";
    }
    greet= () => {
        alert(this.greeting);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 关于淘汰赛改变范围的评论+1.无法弄清楚出了什么问题. (3认同)

Fen*_*ton 5

原型的方法是每个实例上可用的方法.

class Example {
    constructor(private someProperty: string) {

    }

    method() {
        return this.someProperty;
    }
}

var exampleA = new Example('A');
var exampleB = new Example('B');
var exampleC = new Example('C');

console.log(exampleA.method()); // A
console.log(exampleB.method()); // B
console.log(exampleC.method()); // C
Run Code Online (Sandbox Code Playgroud)

每个实例都将拥有somePropertymethod()复制到其原型.您可以使用以下方式检查:

alert(exampleC.hasOwnProperty('someProperty') ? 'Yes' : 'No');
Run Code Online (Sandbox Code Playgroud)

只有当实例没有自己的属性时,JavaScript才会遍历任何依赖链,以便在依赖关系链上方的类中查找属性.

如果您提供的代码在您遇到问题时this我确信我们可以帮助您解决问题.