Function property vs method

前端 未结 4 2028
春和景丽
春和景丽 2020-11-30 11:00

What practical differences are there between defining an interface method:

interface Foo {
    bar(): void;
}

and defining a property with

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 11:28

    It seems that the compiler doesn't seem to care, as all of these are valid:

    interface Foo1 {
        bar(): void;
    }
    
    class Foo1Class1 implements Foo1 {
        bar = () => { }
    }
    
    class Foo1Class2 implements Foo1 {
        bar() { }
    }
    
    interface Foo2 {
        bar: () => void;
    }
    
    class Foo2Class1 implements Foo2 {
        bar = () => { }
    }
    
    class Foo2Class2 implements Foo2 {
        bar() { }
    }
    

    (code in playground)

    The reason for that is probably to do with how that compiles into javascript:

    var Foo1Class1 = (function () {
        function Foo1Class1() {
            this.bar = function () { };
        }
        return Foo1Class1;
    }());
    var Foo1Class2 = (function () {
        function Foo1Class2() {
        }
        Foo1Class2.prototype.bar = function () { };
        return Foo1Class2;
    }());
    

    In both cases an instance of one of those classes will have a property named bar which is a callable function.
    The difference is only that in Foo1Class2 the bar method is part of the prototype which can then be overriden by an extending class.

提交回复
热议问题