Question about javascript object in jquery

A quick question about objects in jquery.

I’m having trouble calling functions in jquery events, here’s how I’m doing it.

var myObj = {}

myObj.test1 = function(str){
     console.log(str);
}

$('.selector').click(myObj.test('test')); //prints test even though nothing has been clicked

//same with
$('.selector').blind({
	click	:	myObj.test('test')
})

the function get’s called fine without any parameters.

something like this will work but $(this) seems to act funny


$(".selector").bind({
	click	:	function(){
		myObj.test('test');
	}
}); //prints test onclick

//if I run test2 the sameway as presented above, this just retruns the myObj Information
myObj.test2 = function(a){
       console.log($(this));
}

Whats the best way to approach $(this)?

How can I call a function directly ex: $(‘.selector’).click(myFunc); And pass in parameters at the same time?

I’ve just started getting into javascript so this is purely an academic endeavor :slight_smile:

thanks

Objects share this in the local scope so the examples you have given won’t work properly because myObj has an instance of this which allows control over the object but not the onclick event. What you need to do is the following so this is set within the correct scope but can be used in the local object scope. See the example below…

var myObj = {}

myObj.test = function(self) {
    console.log(self); // Local scope var set onclick
    console.log(this); // Local scope var set in this object
}

$('.selector').bind('click', function() {
    myObj.test(this);
});

As far as your second question goes I’m not really sure about as i have only ever dealt with passing a function reference and nothing more.

The problem there is that you are executing the function, which means that the function is run straight away, and the returned result from the function is assigned to the click event.

Instead, you should put it inside of an anonymous function, so that the function can then be run later on:


$('.selector').click(function () {
    myObj.test('test')
}); 

oh cool, Thanks for the quick reponse, I was kinda hoping that it would only execute on the click event.

will myObj.test() use parameters passed in by jquery?

ex:

myObj.test = function(i){

console.log(i);

}

$('.selectors').each(myObj.test); //will this display the index(i)?

@SgtLegend: Cool thanks, I’m glad I got that sorted out, javascript has always been a brain teaser for me.

Yes?