You Don't know JS - This & Object Prototypes -Sample code from Book not working

You Don't know JS - This & Object Prototypes -Sample code from Book not working

I am facing problem in running below code which i have copied from the YDKJS book, will appreciate if someone can point how exactly should i run the code from the book.

HTML Code.

    <title>Test Page.</title>
        <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <script src="bootstrap/js/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="bootstrap/js/bootstrap.js" ></script>
        <script src="scripts/main.js"></script>
        <!--<link rel="stylesheet" type="text/css" href="styles/css.txt"/>-->


function Widget(width,height){
	this.width = width || 0;
	this.height = height || 0;
	this.$elem = null;

Widget.prototype.render = function($where){
			width: this.width + "px",
			height: this.height + "px"
		}).appendTo( $where );

//child class
function Button(width,height,label) {
	// "super" constructive call, width, height);
	this.label = label || "Default";
	this.elem = $( "<button>" ).text(this.label);

//make button inherit from widget

Button.Prototype = Object.create(Widget.prototype);

//override inherited render

Button.prototype.render = function($where){
	//super call, $where);
	//this.$ this.onClick.bind( this ) );

Button.prototype.onClick = function(evt){
	console.log("Button '" +  this.label + "' Clicked!");

	var $body = $(document.body);
	var btn1 = new Button(125, 30, "Hello");
	var btn2 = new Button(150, 40, "World!");



You have a couple of typos.

Around line 21:
this.elem should be this.$elem

Around line 27:
Button.Prototype should be Button.prototype


Yes its because of typos, one question though, what is the significane of using $ in code, It can work without $ right?


It’s just another character that you can use in variable names. When I store jQuery objects I often use variables with $ at the front (like in var $submit = $('.submit');), just to make it immediately clear what’s stored in those variables.


So this code is using Jquery right? as when i replace $ from $(document), It fives error saying ready is not a function.

Also Is it necessary to set the this.$elem = null in function Widget?


The code would work the same without it, but IMO it’s probably better to leave it there because Widget.prototype.render uses that same property (so when you inspect that method, you don’t ask where it magically comes from; it’s making the existence of this.$elem more explicit so to speak)


Yes thanks a lot, Now I have understood this, I must say one of the most complex line from the code is in Button.Prototype.render function:
this.$ this.onClick.bind( this ) );