我不是在谈论 C#,但我的问题与之相关。
C# 语法:
IList<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
foreach (var item in list) Console.WriteLine(item); // 1, 2, 3
IList
是一个接口(interface),而 List
是一个类。而且我知道javascript中没有接口(interface)的概念,但我可以使用类来代替。
所以,js 语法如下:
let IList = (function () {
let _T;
class IList {
constructor(T) {
_T = T;
this[_T] = [];
}
Add(item) {
let _this = this;
_this[_T].push(item);
}
*[Symbol.iterator]() {
let _this = this;
let source = _this[_T];
// it doesn't support forEach method
// source.forEach(x => yield x);
for (let s of source) yield s;
}
}
return IList;
}());
let List = (function () {
class List extends IList {
constructor(T) {
super(T);
}
}
return List;
}());
// Usage:
let list = new List('int');
list.Add(1);
list.Add(2);
list.Add(3);
for (let item of list) console.log(item); // 1, 2, 3
我被 IList
类困住了,我不想允许创建它的实例。
let list = new IList('int'); // throw some exception here
如何编辑它?谢谢!
最佳答案
如果直接调用 IList
构造函数而不是通过 super
调用,则在该构造函数中引发异常。
您可以使用 new.target 获取通过 new
调用的函数( which Babel does not yet handle ) 或使用更好支持的 this.constructor
。
顺便说一句,您的方法在私有(private)变量 _T
方面也存在很大的缺陷,该变量当前在 IList
的所有实例之间共享。您可能需要 IList 实例的私有(private)属性(请参阅: "Private properties in JavaScript ES6 classes" )。
完整示例:
let IList = (function () {
let _T;
class IList {
constructor(T) {
if (this.constructor === IList) {
throw new Error('Cannot create an instance of the abstract class IList');
}
_T = T;
this[_T] = [];
}
Add(item) {
let _this = this;
_this[_T].push(item);
}
*[Symbol.iterator]() {
let _this = this;
let source = _this[_T];
// it doesn't support forEach method
// source.forEach(x => yield x);
for (let s of source) yield s;
}
}
return IList;
}());
let List = (function () {
class List extends IList {
constructor(T) {
super(T);
}
}
return List;
}());
// This would throw:
// let iList = new IList('int');
let list = new List('int');
list.Add(1);
list.Add(2);
list.Add(3);
// Uncomment this line to break the example because
// the private _T variable will become "string"
// let list2 = new List('string');
for (let item of list) console.log(item); // 1, 2, 3
关于javascript - 如何创建一个没有实例的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44651430/