有些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
答案 0 :(得分:4)
constructor
属性在原型上定义。
Car.prototype = new Vehicle
覆盖原型并为其分配Vehicle
的实例。所有Vehicle
个实例都会从constructor
继承Vehicle
,Vehicle.prototype
。
答案 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"