在OOP Javascript中设置类的高度和宽度

时间:2012-12-11 22:49:42

标签: javascript oop class size

我是初学者,在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 

1 个答案:

答案 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);