javascript - Automatically call bind() on all instance methods in es6 during constructor -
how can (or possible to) make javascript base class automatically calls bind on each of instance methods during it's constructor?
i tried, without success:
class baseclass { constructor() { // (let in this.__proto__) { // <-- failed (let in this) { if (typeof this[i] === 'function') { this[i] = this[i].bind(this); } } } } class myclass extends baseclass { constructor() { super(); this.foo = 'bar'; } mymethod() { console.log(this.foo); } }
when set break point in constructor, this.mymethod
exists, , exists in this.__proto__
, doesn't in object.getownpropertynames(this)
in neither class's constructor nor base class's constructor.
essentially i'm trying bonus step in this blog post (after conclusion) without needing define or call _bind()
manually.
es6 class methods non-enumerable, you'd have walk prototype chain yourself.
for (let obj = this; obj; obj = object.getprototypeof(obj)){ (let name of object.getownpropertynames(obj)){ if (typeof this[name] === 'function'){ this[name] = this[name].bind(this); } } }
avoiding complexity why "bonus step" explicitly naming things bind. it's going way slower on every single object create.
Comments
Post a Comment