javascript - 创建类方法别名而不注册为属性
问题描述
我正在尝试在类中创建方法别名,此代码工作正常
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
有没有办法在不注册为属性的情况下创建方法别名?
解决方案
您还可以使用private
标志:
class Foo {
bar = "Hello World!";
x() {
console.log(this.bar);
}
#y = this.x;
}
const foo = new Foo(); // Foo {bar: "Hello World!"}
请记住,这是一项新功能,因此它可能不适用于最旧的浏览器
推荐阅读
- angularjs - AngularJs - 路由解析器链接
- python - 使用 Turtle 后如何关闭窗口
- python - 在完整文件路径中搜索用户关键字并根据搜索结果给出输出目录或文件名
- c# - 如何清除 WinForms 中的 DevExpress TimeEdit 控件?
- ms-access - 在一个查询中返回多个组中的前“X”条记录
- angular - 导入 MatDialog 组件时出现以下错误的修复方法是什么?
- sql-server - 在 VB.NET 中增加 SqlCommand.CommandTimeout
- dialogflow-es - 保存的对话如何在 Dialogflow 中工作?
- javascript - 在 React 和 SCSS 中条件渲染列表项的特殊性问题
- r - R for 围绕 tidyverse 管道循环