我是初学者,在javascript中使用OOP编码。
我正在尝试设置一个班级的大小。但是我的代码出错了。
(function($) {
Block = function() {
var self = this;
this.el = $('<div></div>');
}
Block.prototype.appendTo = function(parent) {
this.el.appendTo(parent);
}
Block.prototype.setSize = function(width, height) {
var self = this;
this.width = width;
this.height = height;
}
})(jQuery);
这就是我打电话给班级的方式:
var block1 = new Block();
block1.appendTo('body').setSize(100,100);
在控制台中我得到:
Uncaught TypeError: Cannot call method 'setSize' of undefined
答案 0 :(得分:1)
您在setSize
的返回值上调用appendTo
。但是,appendTo
不返回任何内容(undefined
),因此当您尝试在其上调用setSize
时会抛出错误。
解决方法是从Block
函数返回appendTo
对象,如下所示:
(function($) {
Block = function(width, height) {
this.el = $('<div></div>');
if (width !== undefined && height !== undefined) {
this.width = width;
this.height = height;
}
}
Block.prototype.appendTo = function(parent) {
this.el.appendTo(parent);
return this;
}
Block.prototype.setSize = function(width, height) {
this.width = width;
this.height = height;
}
})(jQuery);