gpt4 book ai didi

javascript - 我可以将 'new' 关键字设为 CoffeeScript 中类的可选关键字吗?

转载 作者:行者123 更新时间:2023-11-29 09:53:00 24 4
gpt4 key购买 nike

在 JavaScript 中,有一个小技巧可以让 new 关键字成为可选的:

function Frob(args) {
if (!(this instanceof Frob)) {
return new Frob(args);
}

// Normal initialization logic
}

这样,您可以使用或不使用 new 关键字实例化一个 Frob:

new Frob('foo'); // a Frob instance
Frob('bar'); // also a Frob instance

有没有办法在 CoffeeScript 中使用 class 关键字来做到这一点?

最佳答案

只需定义一个构造函数:

class Frob
constructor: (args) ->
return new Frob(args) unless this instanceof Frob
### Rest of your init code ###

Output :

var Frob;

Frob = (function() {
function Frob(args) {
if (!(this instanceof Frob)) {
return new Frob(args);
}
}

return Frob;

})();

关于javascript - 我可以将 'new' 关键字设为 CoffeeScript 中类的可选关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18450341/

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