javascript - JS中不能找到原型链中的方法
PHPz
PHPz 2017-04-11 09:02:59
[JavaScript讨论组]
//定义飞船的构造函数
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

学习是最好的投资!

全部回复(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);
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号