Page 1 of 1

Javascript function call .

Posted: Tue Nov 04, 2014 12:27 pm
by gautamz07
The answer might be obvious , but i still don't get it , check out the below snippet :

it has two functions show_items() one as a global function and the other as a function inside temp , i have commented what i get in the console .

Code: Select all

<script type="text/javascript">

var movies = 'Love them !!',
	radio = 'antique';

var temp = {
	movies : 'Love them !! inside temp',
	radio : 'antique.. inside temp',
		show_items : function show_items(){
		console.log(this.movies + " " + this.radio)
	}
}

function show_items(){
	console.log(this.movies + " " + this.radio)
}

show_items();
temp.show_items();

i get the below in the console : 

Love them !! antique
Love them !! inside temp antique.. inside temp

</script>
now when i make one small change I.E. i make the function inside temp a self calling function :

Code: Select all

show_items : function show_items(){
		console.log(this.movies + " " + this.radio)
	}()
check out the code below , i have commented what i get in the console .

Code: Select all

var movies = 'Love them !!',
	radio = 'antique';

var temp = {
	movies : 'Love them !! inside temp',
	radio : 'antique.. inside temp',
		show_items : function show_items(){
		console.log(this.movies + " " + this.radio)
	}()
}

function show_items(){
	console.log(this.movies + " " + this.radio)
}

show_items();

i get the following on the console : 

Love them !! antique
Love them !! antique
Why ?? when i make the function inside temp a self calling function , what exactly changes , or rather what exactly is it calling ??

Re: Javascript function call .

Posted: Tue Nov 04, 2014 8:12 pm
by requinix
Because you have the function defined twice so when you call show_items() you get the latter one which has this==window.

For the other one that you want to keep, don't name it and don't call it. Just use a straight function(){}.

Code: Select all

var temp = {
        movies : 'Love them !! inside temp',
        radio : 'antique.. inside temp',
        show_items : function (){
                console.log(this.movies + " " + this.radio)
        }
}

temp.show_items();