JavaScript this refers to window instead of object inside function -


i confused on javascript this reference situation.

i working on code declare function inside object method. (the reason tidy code inside object method, while keeping functions private method.)

the following experiment re-produce problem.

i found this inside greeting function refers window scope instead of person scope.

var person = {     nickname: "makzan",     sayhi: function() {         console.log(this);         var greeting = function() {             console.log(this);             return "aloha " + this.nickname;         }         console.log(greeting());     } } person.sayhi(); 

(same code in jsfiddle: http://jsfiddle.net/makzan/z5zmm/)

and log result in browser:

> object > window aloha undefined  

in js, know this reference tricky. , can change scope using .call method make code works.

var greeting = (function() {     console.log(this);     return "aloha " + this.nickname; }).call(this); 

however, curious know why default this refer window scope inside greeting method?

thanks in advance help.

this has nothing scope. determined context.

greeting() calls function no context, this default object (window in browser).


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -