[英]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.