我不是在谈论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
是一个接口,而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
我该如何编辑?谢谢!
答案 0 :(得分:1)
如果IList
构造函数直接调用而不是super
调用,则会在new
构造函数中抛出异常。
您可以使用new.target(which Babel does not yet handle)或更好的支持this.constructor
来获取使用_T
调用的函数。
作为旁注,您的方法在私有变量IList
方面也存在很大的缺陷,该变量目前在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
的所有实例中共享。您可能需要IList实例的私有属性(请参阅:"Private properties in JavaScript ES6 classes")。
完整示例:
Getting remote branches...
Seen branch in repository origin/branch1
Seen branch in repository origin/branch2
Seen branch in repository origin/master
Seen 3 remote branches
Checking branch master
Checking branch branch2
Checking branch branch1
Done.
[Tue Jun 20 11:49:46 GMT 2017] Finished branch indexing. Indexing took 2.2 sec
Finished: SUCCESS
&#13;