简体   繁体   English

在JavaScript中,是否可以使用与类函数同名的类getter?

[英]In JavaScript, is it possible to have a class getter with the same name as a class function?

I understand that this may be an anti-pattern, but I'm curious how certain JavaScript libraries have the ability to chain JavaScript functions with optional parenthesis... (eg chalk ) 我知道这可能是反模式,但是我很好奇某些JavaScript库如何能够将JavaScript函数与可选的括号链接起来(例如, 粉笔

An example of this would be... 一个例子是...

let test = (new SomeClass()).initiate.parse(1).end;
let test = (new SomeClass()).initiate(1).parse.end;

Is there a way of doing this? 有办法吗? I thought about maybe trying to do this with getters but the get initiate() of SomeClass was overridden by the class function initiate() . 我想过,也许试图用干将要做到这一点,但get initiate() SomeClass的的是由类函数重载initiate()

No, it is not possible to have a getter and a method with the same name. 不,不可能有一个具有相同名称的吸气剂和方法。

You could achieve what you want though. 您可以实现自己想要的。 One way is to use a Proxy in your getters to make it so that when a further property is accessed, that property of the original object is accessed instead. 一种方法是在您的getter中使用Proxy进行代理,以便在访问其他属性时,改为访问原始对象的该属性。

 class SomeClass { get initiate ( ) { console.log( `Accessed initiate` ); return new Proxy( x => { console.log( `Called initiate with arg ${x}` ); this.stored = x; return this; }, { get: (_,prop) => this[prop] } ); } get parse ( ) { console.log( `Accessed parse` ); return new Proxy( x => { console.log( `Called parse with arg ${x}` ); this.stored = x; return this; }, { get: (_,prop) => this[prop] } ); } get end ( ) { return this.stored; } } console.log( (new SomeClass).initiate(2).parse.end ); console.log( (new SomeClass).initiate.parse(3).end ); console.log( (new SomeClass).initiate(5).parse(7).end ); 

I would heavily recommend taking a look at how chai or other assertion libraries do this. 我强烈建议您看一下chai或其他断言库如何做到这一点。 For the code, you're looking for, you can look here . 对于代码,您正在寻找,可以在这里查看

What they do is they define an Assertion class and define methods and properties separately. 他们要做的是定义一个Assertion类,并分别定义方法和属性。 From there, they use getters as you mentioned to achieve what you are trying to do with properties but they also keep methods separate (see addMethod ) 从那里开始, 它们使用您所提到的getter来实现您要对属性执行的操作,但是它们还将方法分开(请参见addMethod

Another question you can look at is How does the expect().to.be.true work in Chai? 您可以查看的另一个问题是,Chai中的Expect()。to.be.true如何工作的? where the accepted answer has a code example of how to get something very basic working. 那里接受的答案有一个代码示例,说明如何获得一些基本的工作。

I would be conscientious about having methods and properties the same name though. 我将尽全力使方法和属性具有相同的名称。 That can confuse a lot of people who are using your class as a consumer. 这会使许多将您的班级用作消费者的人感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM