首页 > 解决方案 > 创建类方法别名而不注册为属性

问题描述

我正在尝试在类中创建方法别名,此代码工作正常

class Foo {
    bar = "Hello World!";

    x() {
        console.log(this.bar);
    }

    y = this.x;
}

const foo = new Foo();
foo.y(); // prints out "Hello World"

但是,y成为 的属性foo,例如,如果我这样做

console.log(foo);

它会显示

Foo { bar: 'Hello World!', y: [Function: x] } // I want y to be the method and not shown on the console.log like `x`, not property of foo

有没有办法在不注册为属性的情况下创建方法别名?

标签: javascripttypescriptalias

解决方案


您还可以使用private标志:

class Foo {
    bar = "Hello World!";

    x() {
        console.log(this.bar);
    }

    #y = this.x;
}

const foo = new Foo(); // Foo {bar: "Hello World!"}

游乐场链接

请记住,这是一项新功能,因此它可能不适用于最旧的浏览器


推荐阅读