理解Javascript原型链和继承 - 示例

时间:2015-06-25 21:51:19

标签: javascript

有些javascript忍者可以向我解释为什么我的构造函数在这里拙劣吗?我觉得我正在正确实现原型链。我知道我可以使用Object.create,但我只是想了解为什么这不起作用。

var Vehicle = function() {}
Vehicle.prototype.accelerate = function() { console.log('VRRRROOOOOOOM') }
Vehicle.prototype.brake = function() { console.log('SCREEEEECH') }

var Car = function() {}
Car.prototype = new Vehicle
Car.prototype.openTrunk = function() { console.log('POP') }
Car.prototype.closeTrunk = function() { console.log('CLUNK') }

// Test
var mazda = new Car
console.log(mazda) // prototype chain is right
console.log(mazda.constructor === Car) // should be true
console.log(mazda.constructor === Vehicle) // should be false

https://jsfiddle.net/6j43r8qg/1/

2 个答案:

答案 0 :(得分:4)

constructor属性在原型上定义。

Car.prototype = new Vehicle

覆盖原型并为其分配Vehicle的实例。所有Vehicle个实例都会从constructor继承VehicleVehicle.prototype

enter image description here

答案 1 :(得分:0)

此外,我认为console.log(mazda) // prototype chain is right console.log(mazda instanceof Car) // should be true console.log(mazda instanceof Vehicle) // should be *true?!* 将是检查某事物是否是某种东西的方法

android:hardwareAccelerated="true"