简体   繁体   中英

JavaScript object inheritance issue

I'm a beginner with JavaScript Objects and Prototypes and trying to develop my first " multi-level inherited" JS Objects, an unexpected issue came up. This is my code:

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');
};

Why when I try to call the group manager, it prints only the sayHelloGeneral function?

var GM = new GroupManager;

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

It seems to be working fine. See the snippet below

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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