简体   繁体   English

JavaScript 对象继承问题

[英]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.我是 JavaScript 对象和原型的初学者,在尝试开发我的第一个“多级继承”JS 对象时,出现了一个意想不到的问题。 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?为什么当我尝试调用组管理器时,它只打印 sayHelloGeneral 函数?

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

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

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