在我正在开发的 AngularJS 模块中,我有一个Canvas
类定义为:
angular.module("myModule", [])
.factory("Canvas", function() {return Canvas;});
var Canvas = function(element, options) {
this.width = options.width || 300;
this.height = options.height || 150;
this.HTMLCanvas = $(element).get(0);
this.HTMLCanvas.width = canvas.width;
this.HTMLCanvas.height = canvas.height;
this.objects = [];
//Initialize canvas
this.init();
}
Canvas.prototype.init = function() {/*...*/};
Canvas.prototype.otherMethod = function() {/*...*/};
现在,Canvas
该类永远不会从模块内部实例化,而是从 AngularJS 控制器实例化,如下所示:
angular.module("myApp.controllers", ["myModule"])
.controller("MainCtrl", ["Canvas", function(Canvas) {
var canvas = new Canvas("#canvas", {/*options object*/});
//...
}]);
到目前为止,一切都像一个魅力。但是后来我意识到我需要$q
画布对象中的服务,并且由于我不想将其注入我的控制器然后将其传递给Canvas
构造函数,所以我想像这样修改我的模块:
angular.module("myModule", [])
.factory("Canvas", ["$q", function(q) {
var that = this;
that.q = q;
return function() {
Canvas.apply(that, arguments);
};
}]);
var Canvas = function(element, options) {
console.log(this.q, element, options);
this.width = options.width || 300;
this.height = options.height || 150;
this.HTMLCanvas = $(element).get(0);
this.HTMLCanvas.width = canvas.width;
this.HTMLCanvas.height = canvas.height;
this.objects = [];
//Initialize canvas
this.init();
}
Canvas.prototype.init = function() {/*...*/};
Canvas.prototype.otherMethod = function() {/*...*/};
初始console.log
正确地记录了$q
服务和Canvas
的原始参数,element
并且options
,但在调用其init
方法时中断:
TypeError: undefined is not a function
我想那是因为this
不再是匿名函数的实例,Canvas
而是匿名函数的实例function(q) {...}
。
关于如何Canvas
使用该属性实例化新对象q
并仍然保留类的方法的任何提示?
编辑
我稍微修改了我的代码,以便更好地了解我想要实现的目标:
angular.module("myModule", [])
//.factory("Canvas", function() {return Canvas;})
//.factory("Canvas", ["$q", CanvasFactory])
function CanvasFactory(q) {
var canvas = this;
canvas.q = q;
return function() {
Canvas.apply(canvas, arguments);
};
}
var Canvas = function(element, options) {
console.log(this instanceof Canvas, typeof this.q !== "undefined");
};
如果我取消注释第一个工厂,console.log
yield true false
,而第二个工厂 yield false true
。我的目标是 get true true
,这意味着它this
实际上是Canvas
该类的一个实例并定义了q
属性。非常感谢任何提示。