javascript - JS中不能找到原型链中的方法
PHPz
PHPz 2017-04-11 09:02:59
0
1
256
//定义飞船的构造函数 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这些方法呢?求解。谢谢。

PHPz
PHPz

学习是最好的投资!

reply all (1)
大家讲道理

问题出在你的构造函数上面,因为你在函数内直接return了它的getId方法,因此后续的针对ship的原型绑定都直接失效! 过早的return 是主要原因
这是你绑定之后a对象的属性和构成: 可以看到,并没有那几个方法!

//定义飞船的构造函数 function Ship (id) { var id = id; this.getId = function(){ return id; } }

这样绑定在不修改你之前返回值和获取getId方法的前提下,是最好的,

function Ship (id) { this.id = id; this.getId = function(){ return id; } } //获取上面的id,修改prototype里面的runship方法: runShip : function(){ console.log(this.id); }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!