简体   繁体   中英

Setting height en width of a Class in OOP Javascript

I'm a beginner with OOP coding in javascript.

I'm trying to set a size of a class. But i got an error in my code.

    (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);

This is how i call the class:

var block1 = new Block();
block1.appendTo('body').setSize(100,100);

In the console i get:

Uncaught TypeError: Cannot call method 'setSize' of undefined 

You are calling setSize on the return value of appendTo . However, appendTo returns nothing ( undefined ) and as such it throws an Error when you try and call setSize on it.

The solution to this is to return the Block object from your appendTo function, like so:

(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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM