我正试图在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?
在Vans.obj[ '6789' ]
上调用drive
方法时,JS首先检查对象本身是否具有此属性。它没有,所以它检查了它的原型Cars.obj[ '12345' ]
。它也没有这个方法,所以检查了那个对象的原型Car.prototype
。该方法在那里找到并在Vans.obj[ '6789' ]
对象上执行。
如果在执行此行时未定义Cars.obj[ '12345' ]
:
Van.prototype = Object.create ( Cars.obj[ '12345' ] )
JS会抛出一个错误,因为不允许undefined
作为Object.create
方法的输入。