Page 1 of 1

Need help understanding "this"

Posted: Tue Oct 29, 2013 4:36 pm
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() } );  

Re: Need help understanding "this"

Posted: Tue Oct 29, 2013 6:17 pm
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.

Re: Need help understanding "this"

Posted: Thu Aug 21, 2014 6:02 pm
by thinsoldier
Thanks requinix.