Search code examples
javascriptprototypal-inheritancemodular

Modular JS and Prototypal Inheritance


I'm trying to wrap my head around prototypal inheritance in JS. Is it possible for a module to borrow from another module's prototype?

The only way I've managed this so far is by accessing it down the prototype chain. Let's say, the first module hasn't created anything yet, is my second module just sol?

Here's an example:

var Cars = (function ( make, serial ) {
	var obj = {};
	
	var Car = function () {
		this.make = make;
		this.serial = serial;
	}

	Car.prototype.drive = function () {
		console.log('vrrrooom')
	}

	obj[ serial ] = new Car()
	return {obj:obj}

}( 'Toyota', '12345' ))

var Vans = (function ( make, serial ){
	var obj = {}

	var Van = function () {
		this.make = make;
		this.serial = serial;
	}

	Van.prototype = Object.create ( Cars.obj[ '12345' ] )

	obj[ serial ] = new Van()
	return {obj:obj}

}( 'Ford', '6789' ))

// So the Toyota drives?
console.log( Cars.obj )
Cars.obj[ '12345' ].drive() // Cool!


// Maybe my Ford can too?
console.log( Vans.obj )
Vans.obj[ '6789' ].drive() // Cool, but what if there were no Cars?


Solution

  • When drive method is called on the Vans.obj[ '6789' ], JS first checks if the object itself has this property. It doesn't, so it checks its prototype Cars.obj[ '12345' ]. It also doesn't have this method, so the prototype of a that object, Car.prototype, is checked. The method is found there and executed on the Vans.obj[ '6789' ] object.

    If Cars.obj[ '12345' ] was not defined ad the point of executing this line:

    Van.prototype = Object.create ( Cars.obj[ '12345' ] )
    

    JS would throw an error, since undefined is not allowed as the input to the Object.create method.