Javascript function call .

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Javascript function call .

Post 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 ??
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Javascript function call .

Post 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();
Post Reply