Niraj Chauhan

Niraj Chauhan

#father #husband #SoftwareCraftsman #foodie #gamer #OnePiece #naruto

Javascript Mixin

Posted by on

In simple words reusing object between different classes. You can also take it as an Interface with implemented methods. This will include all the methods and properties in the class without inheriting it.

So lets start with simple Prototypes.

function Ferarri(){
	this.wheels = "4";
}

Ferarri.prototype.color = function(){
	return "red";
}


function Ducati(){
	this.type = "bike";
}

Ducati.prototype.color = function(){
	return "black";
}

Now lets create an object which can also be viewed as an Interface.

var Vehicle = {
	totalWheels: function(){
		return this.wheels;
	},
	getType: function(){
		return this.type
	}
};

So our object is ready, now we just need to extend it with our classes. You can easily do this using jQuery or underscore js libraries.

$.extend(Ferarri.prototype, Vehicle);
$.extend(Ducati.prototype, Vehicle);