如何创建一个没有实例的类?

时间:2017-06-20 11:10:18

标签: javascript

我不是在谈论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

我该如何编辑?谢谢!

1 个答案:

答案 0 :(得分:1)

如果IList构造函数直接调用而不是super调用,则会在new构造函数中抛出异常。

您可以使用new.targetwhich 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")。

完整示例:

&#13;
&#13;
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;
&#13;
&#13;