Need help understanding "this"

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Need help understanding "this"

Post by thinsoldier »

I've set up a small example script:
http://codepen.io/anon/pen/GIaor

At the bottom of the Javascript I have 3 example lines.

Could someone explain to me why B fails and why C works?


Code: Select all

<html>
<head>
...jquery...etc...
</head>
<body>

<p class="delete-button"> [x] Delete Something</p>

</body>
</html>

Code: Select all

var MyThing = {

	settings: {
		x_buttons: null
	},

	init: function() {
		this.settings.x_buttons = $('.delete-button');
		this.bindUIActions();
	},
	
	bindUIActions: function() {
		this.settings.x_buttons.click( this.confirmDeletion );
	},

	confirmDeletion: function(event)
	{
		var ask = confirm('Are you sure you want to delete this entry?');
		if( false === ask){ event.preventDefault(); }
	}
};

// A: works
// MyThing.init();

// B: fails
// Cannot set property 'x_buttons' of undefined
// this.settings is undefined
// $(document).ready( MyThing.init );

// C: works
 $(document).ready( function(){ MyThing.init() } );  
Warning: I have no idea what I'm talking about.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Need help understanding "this"

Post by requinix »

In Javascript "this" can vary according to how the function is called. It's not the object where the code executing lives (like in most languages) but more of a context. With the second example the context is document, and when you passed init as a function all you told Javascript to do was to execute that function: its "this" will be document.

init is not a kind of object method but is really just a function that lives in an object.

This page seems like a good read.

Typically with ready() and similar functions you pass a whole new function - they're cheap in Javascript. Within that function you do whatever: execute code, call other functions, whatever.
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Re: Need help understanding "this"

Post by thinsoldier »

Thanks requinix.
Warning: I have no idea what I'm talking about.
Post Reply