模块化JS和原型继承

时间:2016-04-14 19:33:03

标签: javascript prototypal-inheritance modular

我正试图在JS中围绕prototypal inheritance。模块是否可以从另一个模块的原型借用?

到目前为止,我管理此问题的唯一方法是通过prototype chain访问它。比方说,第一个模块还没有创建任何东西,我的第二个模块是sol?

以下是一个例子:

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?

1 个答案:

答案 0 :(得分:1)

drive上调用Vans.obj[ '6789' ]方法时,JS首先检查对象本身是否具有此属性。它没有,所以检查它的原型Cars.obj[ '12345' ]。它也没有这种方法,因此检查了该对象Car.prototype的原型。该方法在那里找到并在Vans.obj[ '6789' ]对象上执行。

如果未定义Cars.obj[ '12345' ],则执行此行:

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

JS会抛出错误,因为undefined不允许作为Object.create方法的输入。