尝试使用Browserify在CommonJS模块中实现单例模式.至今:
// foo.js
var instance = null;
var Foo = function(){
if(instance){
return instance;
}
this.num = 0;
return instance = new Foo();
}
Foo.prototype.adder = function(){
this.num++;
};
module.exports = Foo();
Run Code Online (Sandbox Code Playgroud)
// main.js
var foo = require('./foo.js');
console.log(foo.num); // should be 0
foo.adder(); // should be 1
var bar = require('./foo.js');
console.log(bar.num); // like to think it'd be 1, not 0
Run Code Online (Sandbox Code Playgroud)
第一个问题是,maximum call stack exceeded当我在浏览器中加载构建的JS文件时出现错误,但其次,我是否正确地接近了这个?这可能吗?
C:\ dev\OpenCMS\Website\Frontend\Scripts\libs\sinnovations> tsc sinnovations.listv iewbase.ts --module amd C:/dev/OpenCMS/Website/Frontend/Scripts/libs/sinnovations/sinnovations.listviewb ase. ts(11,5):错误TS2025:导出类的公共属性"列"具有或正在使用私有类型"KnockoutObservableArray".
/// <reference path="../../typings/knockout/knockout.d.ts" />
import ko = require('knockout');
interface Column {
label: string;
}
var _templateBase = '/Frontend/Templates/ListView/';
class ListViewBase<T> {
columns: KnockoutObservableArray<Column> = ko.observableArray([]);
rows: KnockoutObservableArray<T> = ko.observableArray([]);
constructor(public templateHeaderRow = _templateBase+'DefaultTableHeaderTemplate', public templateBodyRow = _templateBase + 'DefaultTableRowTemplate') {
}
addColumn(column: Column) {
this.columns.push(column);
}
addRow(row: T) {
this.rows.push(row);
}
static configure(templateBase) {
_templateBase = templateBase;
}
}
export = ListViewBase;
Run Code Online (Sandbox Code Playgroud)
我理解错误,但不知道如何获得上述效果.任何人都有一个解决方案来导出一个导出为export = class的类的接口?