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
setSizeon the return value ofappendTo. However,appendToreturns nothing (undefined) and as such it throws an Error when you try and callsetSizeon it.The solution to this is to return the
Blockobject from yourappendTofunction, like so: