//定义飞船的构造函数
function Ship (id) {
var id = id;
return {
getId : function(){
return id;
}
}
}
//ship的prototype重定义
Ship.prototype = {
//因为Ship.prototype覆盖原来的prototype所以constructor也被覆盖,要重新指定一下。
constructor:Ship,
runShip:function (id){},
stopShip:function (id){},
destroyShip:function (id){},
powerUp:function (id){}
}
var a = new Ship(0);
console.log(ships[0].constructor === Ship);//false
console.log(Ship.prototype.constructor === Ship);//true
console.log(ships[0].constructor.prototype.constructor === Ship);//false
这样的结果导致a变量不能访问Ship原型链中的方法,哪里有问题导致的呢?怎么样才能访问到Ship.prototype中的runShip这些方法呢?求解。谢谢。
问题出在你的构造函数上面,因为你在函数内直接return了它的getId方法,因此后续的针对ship的原型绑定都直接失效! 过早的return 是主要原因

这是你绑定之后a对象的属性和构成: 可以看到,并没有那几个方法!
这样绑定在不修改你之前返回值和获取getId方法的前提下,是最好的,