在这里,我尝试使用谷歌闭包创建一个包含单个圆圈的简单绘图区域小部件。
我通过在html脚本标记中调用sketcher.load()
来加载它并收到错误:
Uncaught TypeError: Cannot set property 'Widget' of undefined
- 什么不对吗?
goog.provide('sketcher');
goog.require('goog.dom');
goog.require('goog.graphics');
goog.require('goog.ui.Component');
var sketcher = {};
sketcher.prototype.Widget = function(el){
goog.ui.Component.call(this);
this.parent_ = goog.dom.getElement(el);
this.g_ = new goog.graphics.createGraphics(600, 400);
this.appendChild(this.g_);$
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(1,'black');
circle = this.g_.drawCircle(300, 200, 50, stroke, fill);
this.g_.render(this._parent);
};
goog.inherits(sketcher.Widget, goog.ui.Component);
sketcher.prototype.load = function(){
var canvas = goog.dom.createDom('div', {'id':'canvas'});
goog.dom.appendChild(document.body, canvas);
var widget = new sketcher.Widget(canvas);
};
答案 0 :(得分:2)
第一个问题:sketcher是一个命名空间,因为你goog.provide它。您无需再次声明它。
第二个问题:sketcher.Widget应该是,而不是sketcher.prototype.Widget。只有功能有原型;您应该返回并查看对象如何在JavaScript中工作,除非这只是一个错字。它看起来应该是这样的。
goog.provide('sketcher');
goog.require('goog.dom');
goog.require('goog.graphics');
goog.require('goog.ui.Component');
/**
* My sketcher widget.
* @param {Element} e1
* @constructor
*/
sketcher.Widget = function(el){
goog.ui.Component.call(this);
this.parent_ = goog.dom.getElement(el);
this.g_ = new goog.graphics.createGraphics(600, 400);
this.appendChild(this.g_);$
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(1,'black');
circle = this.g_.drawCircle(300, 200, 50, stroke, fill);
this.g_.render(this._parent);
};
goog.inherits(sketcher.Widget, goog.ui.Component);
sketcher.prototype.load = function(){
var canvas = goog.dom.createDom('div', {'id':'canvas'});
goog.dom.appendChild(document.body, canvas);
var widget = new sketcher.Widget(canvas);
};
答案 1 :(得分:0)