How to use base class methods in a subclass of a Builtin JavaScript class in javascript -
in c# example can extend framework type , assign expression type , retain members of base type have extended methods.
i'm trying inherit sentence
range
.
note suggested duplicate doesn't apply here because range
not susceptible these techniques.
how can achieve in javascript? have:
/* namespace */ var webpagereader = webpagereader || {}; /* classes */ webpagereader.sentence = function(range) { this.setstart(range.startcontainer, range.startoffset); // bombs here this.setend(range.endcontainer, range.endoffset); }; function test(){ webpagereader.sentence.prototype = new range(); var dom = new webpagereader.dom(); var s = new webpagereader.sentence(dom.getselectedrange()); alert(s.endoffset) ; } webpagereader.dom = function() { /* public methods */ this.getselectedrange = function() { var sel; if (window.getselection) { sel = window.getselection(); if ((sel.type == "range" || allowcaretselection) && sel.rangecount) { return sel.getrangeat(0); } } return null; } }
this gives error:
uncaught typeerror: illegal invocation
attempt #2
when change code this:
/* namespace */ var webpagereader = webpagereader || {}; /* classes */ webpagereader.sentence = function(range) { range.call(this); }; function test(){ webpagereader.sentence.prototype = new range(); var dom = new webpagereader.dom(); var s = new webpagereader.sentence(dom.getselectedrange()); alert(s.endoffset) ; }
i error
uncaught typeerror: failed construct 'range': please use 'new' operator, dom object constructor cannot called function.
you not subclassing properly. should use es6 classes.
var webpagereader = { dom: function() { this.getselectedrange = function() { if (!window.getselection) return null; return window.getselection().getrangeat(0); } }, sentence: class extends range { constructor(range) { super(); this.setstart(range.startcontainer, range.startoffset); this.setend(range.endcontainer, range.endoffset); } } }; document.body.addeventlistener('click', function() { var dom = new webpagereader.dom(); var s = new webpagereader.sentence(dom.getselectedrange()); console.log(s.endoffset); });
select text
it works because super()
initializes instance real range
. in es5 can things making instance inherit range.prototype
, not enough real range
instance. , range
methods can called on real range
instances.
Comments
Post a Comment