javascript - Context of "this" inside private method -
while working private methods in javascript, encountered wired problem. inside private method "this" reference returning handle window object instead of function it's contained in.
here's code, i'm referring
function mycomponent(elem) { alert(this.constructor.name) //returns reference mycomponent function privatemethod() { alert(this.constructor.name) //returning window object, instead of privatemethod function reference } privatemethod() } new mycomponent(document.createelement('span'))
i managed solve bug introducing reference "self" mycomponent function.
function mycomponent(elem) { var self = this; alert(this.constructor.name) //returns reference mycomponent function privatemethod() { alert(self.constructor.name) //after passing "self" reference working } privatemethod() } new mycomponent(document.createelement('span'))
but 1 thing still baffles me how "this" reference in private method returning handle window object.
the reference of this
depends on type of function invocation. have invoked privatemethod()
using function form or simple call , hence this
in privatemethod()
refer global object.instead if had used constructor form invoke privatemethod()
(i.e new privatemethod()
) this
referring function contained in.
checkout simple call topic in mdn
so
function mycomponent(elem) { alert(this.constructor.name) //returns reference mycomponent function privatemethod() { alert(this.constructor.name) //returns privatemethod function reference } new privatemethod() } new mycomponent(document.createelement('span'))
Comments
Post a Comment