oop - OO JavaScript call parent method -


i've been trying grips oo javascript , created simple example.

function basepage(name) {     this.init(name); }  basepage.prototype = {     init: function(name) {        this.name = name;      },     getname: function() {         return this.name;     } }  function faqpage (name, faq) {     this.init(name, faq); }  faqpage.prototype = new basepage();  faqpage.prototype = {     init: function(name, faq) {         basepage.prototype.init.call(this, name);         this.faq = faq;      },     getfaq: function() {         return this.faq;     } }  var faqpage = new faqpage('faq page', 'faq');  var text = faqpage.getname() + ' ' + faqpage.getfaq(); $('body').text(text); 

the result of running results in following message:

uncaught typeerror: object #<object> has no method 'getname'

what know how can call method getname() in super class without having override , call in sub class?

also if if think approach bad/good.

i feel pain. others have mentioned getname undefined because override prototype of faqpage. hence i'll not reiterate explanation.

that being said agree it's encapsulate prototype methods in single scope. perhaps should use javascript library purpose. smallest 1 out there augment. in fact it's 17 lines long:

function.prototype.augment = function (body) {     var base = this.prototype;     var prototype = object.create(base);     body.apply(prototype, array.from(arguments, 1).concat(base));     if (!object.ownpropertyof(prototype, "constructor")) return prototype;     var constructor = prototype.constructor;     constructor.prototype = prototype;     return constructor; };  (function funct() {     var bind = funct.bind;     var bindable = function.bindable = bind.bind(bind);     var callable = function.callable = bindable(funct.call);     object.ownpropertyof = callable(funct.hasownproperty);     array.from = callable([].slice); }()); 

here's how code if used augment:

var basepage = object.augment(function () {     this.constructor = function (name) {         this.name = name;     };      this.getname = function () {         return this.name;     }; });  var faqpage = basepage.augment(function (base) {     this.constructor = function (name, faq) {         base.constructor.call(this, name);         this.faq = faq;     };      this.getfaq = function () {         return this.faq;     }; }); 

then may use would:

var faqpage = new faqpage("faq page", "faq"); var text = faqpage.getname() + " " + faqpage.getfaq(); $("body").text(text); 

hope helps.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -