Javascript closure with new and this -
i playing new, this, , javascript , ran across , have no idea why javascript behaves way. wrapping head around great.
lets have function:
function x() { this.q = function() { console.log(this); }; console.log(this); }
this works expect:
var x = new x(); => x {q: function} x.q(); => x {q: function}
but not act expect:
function func(f) { f(); } var x = new x(); => x {q: function} func(x.q); => window {top: window, window: window, location: location, external: object, chrome: object…} // expected return "x {q: function}" // works... func(function() {x.q()}); => x {q: function}
i seem misunderstanding javascript because way behaves in case nothing how expect to.
because context (this
) of function set how call it in javascript not where declared other languages.
so when call function f()
there no context defaults window
when call x.q()
context x
instance.
if called function like:
obj.something.deep.property.func();
in case context (this
) of function whatever property
is.
(note: strict mode if no context determined this
undefined
, not window
)
Comments
Post a Comment