2015-10-09 192 views
2

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

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 
+0

http://jsfiddle.net/gvhmfoux/ –

+0

为me..where做工精细的片段是你的'的SayHello()'? –

+1

对不起,它是'sayHelloGeneral'。修正:) –

回答

1

它似乎工作正常。见下面

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

+0

谢谢你们!我意识到问题出在我的代码 'FormTools.prototype.sayHelloForm'是'FormTools.prototypesayHelloForm'。 当然,上面只是一个例子,我的代码比我愚蠢的例子要大得多:)非常感谢 –