繁体   English   中英

JavaScript 对象继承问题

[英]JavaScript object inheritance issue

我是 JavaScript 对象和原型的初学者,在尝试开发我的第一个“多级继承”JS 对象时,出现了一个意想不到的问题。 这是我的代码:

var Utils = function () {};
Utils.prototype = {
    sayHelloGeneral: function(){
        console.log('hello');
    }
};

var FormTools = function () {
    Utils.call(this);
    this.fields = [];
};
FormTools.prototype = Object.create(Utils.prototype);
FormTools.prototype.constructor = FormTools;
FormTools.prototype.sayHelloForm= function (fields) {
    console.log('hello form');
};

function GroupManager(value) {
    FormTools.call(this);

    this.val = typeof values === 'undefined' ? 1 : value;
};
GroupManager.prototype = Object.create(FormTools.prototype);
GroupManager.prototype.constructor = GroupManager;
GroupManager.prototype.helloGroupManager= function (givenValue) {
    console.log('Hello group manager');
};

为什么当我尝试调用组管理器时,它只打印 sayHelloGeneral 函数?

var GM = new GroupManager;

GM.sayHelloGeneral(); //->ok
GM.helloGroupManager(); //--> ok
GM.sayHelloForm(); //->sayHelloForm is not a function

它似乎工作正常。 请参阅下面的片段

 var Utils = function () {}; Utils.prototype = { sayHelloGeneral: function(){ console.log('hello'); } }; var FormTools = function () { Utils.call(this); this.fields = []; }; FormTools.prototype = Object.create(Utils.prototype); FormTools.prototype.constructor = FormTools; FormTools.prototype.sayHelloForm= function (fields) { console.log('hello form'); }; function GroupManager(value) { FormTools.call(this); this.val = typeof values === 'undefined' ? 1 : value; }; GroupManager.prototype = Object.create(FormTools.prototype); GroupManager.prototype.constructor = GroupManager; GroupManager.prototype.helloGroupManager= function (givenValue) { console.log('Hello group manager'); }; var GM = new GroupManager; //GM.sayhello(); //->ok---> should be sayHelloGeneral() GM.sayHelloGeneral(); GM.helloGroupManager(); //--> ok GM.sayHelloForm(); //->Works fine too

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM