Javascript

Accessing parent prototype functions from Child

Consider the following code: function Parent() {} Parent.prototype.display = function() { console.log(‘Parent’); } function Child() {} Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; Child.prototype.display = function() { console.log(‘Child’); } var c = new Child(); c.display(); // ‘Child’ In the above code, the final line will print ‘Child’ because c is an object of ‘Child’. Now, if… Continue reading Accessing parent prototype functions from Child

Javascript

Creating abstract class in Javascript

An abstract class is a ‘class’ that is used just for inheritance. We should not be creating objects directly from abstract classes. Here is the code: function Car(name) { if(this.constructor === Car) { throw ‘Cannot instantiate abstract class’; } this.name = name; } function i12() { Car.call(this, ‘i12′); } The key here is the ‘constructor’… Continue reading Creating abstract class in Javascript

Javascript

How to create a revocable function to grant/revoke access to any other function?

The following code will show you how to create a function ‘revocable’ that will be used to grant/revoke access to other functions. The function that will be tested here is the add function to add 2 numbers. But the ‘revocable’ function is good enough to work for other functions as well. function add (x, y)… Continue reading How to create a revocable function to grant/revoke access to any other function?

Javascript

Highlight all occurrences of text in a container

Here is the JQuery code to highlight all occurrences of a given text in a container: $(“.container:contains(‘Google’)”).html(function(_, html) { return html.replace(/(Google)/g, ‘<span style=”background-color: yellow;”>$1</span>’); }); The above block will change all occurences of the text ‘Methods’ within an element of class ‘container’ and make the background color of the text yellow by inserting a new… Continue reading Highlight all occurrences of text in a container

Javascript

Classical inheritance in JS using Object.create()

function Shape() { this.x = 0; this.y = 0; } Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.log(“x : ” + this.x); //x: 1 console.log(“y : ” + this.y); //y: 1 }; function Rectangle() { Shape.call(this); } Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log(rect instanceof Rectangle);… Continue reading Classical inheritance in JS using Object.create()