gpt4 book ai didi

javascript - 使用 ES6 语法定义类方法属性

转载 作者:行者123 更新时间:2023-12-03 07:03:58 25 4
gpt4 key购买 nike

在 ES5 语法中,类 Foo 的方法 bar 具有属性 flag 可以这样定义:

function Foo() {};
Foo.prototype.bar = function() { console.log('bar invoked'); };
Foo.prototype.bar.flag = true;

我可以混合使用 ES5 和 ES6 语法并执行:

class Foo {
bar() {
console.log('bar invoked');
};
};
Foo.prototype.bar.flag = true;

或者只使用 ES6 语法做:

class Foo {
bar() {
this.bar.flag = true;
console.log('bar invoked');
};
};

如果我必须选择,我会选择第二个选项,但我不喜欢在其定义中包含方法名称的冗余。有没有更好的办法?

最佳答案

如果你能超越 ES2015 并且不怕使用实验性的东西,你可以玩装饰器。 Babel repl .

class Foo {
@flag
bar() {
console.log('bar invoked');
};
};

function flag(target) {
target.descriptor.value.flag = true;
return target;
}


const foo = new Foo()

console.log(foo.bar.flag)

关于javascript - 使用 ES6 语法定义类方法属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64282855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com