Sunday, 15 April 2012

Javascript: Explanation of the THIS keyword -



Javascript: Explanation of the THIS keyword -

this question has reply here:

how “this” keyword work? 13 answers

can explain this keyword in javascript? preferably in plain english language without quoting online sources or textbook. i'm pretty sure read through already. still haven't quite grasped concept yet.

i understand this can have several different meanings, depending on how , when it's used.

for instance, read refer global object in cases. can explain different situations meaning of this alter , how it's used?

a improve way @ "how functions called in javascript?"

internally there function primitive known "[[call]]" have interface in function.prototype.call(thisarg, arguments...) that's i'll utilize here.

every time phone call function in javascript you're writing syntax convert equivalent function.call statement, , it's passing in thisarg you. depends purely on way phone call function , not on other object oriented concepts. 1 of main confusions programmers used way class-based object semantics work in other languages have when come javascript.

in case of function called in global context:

function foo(a) { console.log(a); homecoming this; } foo(5); // equivalent foo.call(window, 5); // outputs 5, returns (window)

in case of function called as if linked object (dot syntax):

var o = { foo: function(a) { console.log(a); homecoming this; } }; o.foo(5); // equivalent o["foo"].call(o, 5) // outputs 5, returns (object(o))

that's there it. notice can same function different way:

var x = o.foo; x(5); // equivalent x.call(window, 5); // outputs 5, returns (window)

and exact same function has no knowledge of beingness related in way @ o created with.

in plain english language think topic can get:

if phone call function without putting dot in front, this window (the global object). if dot in front, this object in front end of dot.

if don't way works, can simulate different behavior in variety of ways (like function.prototype.bind or passing own thisarg call or apply).

small print: in ecmascript strict mode, window passed in examples above, instead pass undefined. , "dot in front" i'm speaking practically, o["foo"](6), beingness same o.foo(6) same thing this.

javascript

No comments:

Post a Comment