【问题标题】:JavaScript object inheritance issueJavaScript 对象继承问题
【发布时间】:2015-10-09 10:16:23
【问题描述】:

我是 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

【问题讨论】:

  • 我工作得很好..你的sayhello()在哪里?
  • 抱歉是sayHelloGeneral。固定:)

标签: javascript object javascript-objects


【解决方案1】:

它似乎工作正常。见下面的sn-p

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

【讨论】:

  • 谢谢大家!我意识到问题在于我的代码FormTools.prototype.sayHelloFormFormTools.prototypesayHelloForm。当然上面只是一个例子,我的代码比我愚蠢的例子要大得多:) 非常感谢
猜你喜欢
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多