user2413333
user2413333

Reputation: 1405

When caching vars, what is the best way to call it?

If you cache a var:

var something = $('#something');

I have seen that being used later as:

$(something).doAction();
something.doAction();

Is there a difference in using either? I have started using something.doAction() as it looks cleaner and easier to read. But I'd like to know if this could cause any problems?

Upvotes: 0

Views: 63

Answers (4)

Misters
Misters

Reputation: 1347

There is just hold this a jquery object to use it later or avoid repetition.

var $button = $('#button');

$button.click(function(){
//some code here
});

//now applying some style to it
$button.css({color:"#ccc",background:"#333"});

Or could be replace with

var $button = $('#button').css({color:"#ccc",background:"#333"});

$button.click(function(){
//some code here
});

Or

$('#button').css({color:"#ccc",background:"#333"}).click(function(){
//some code here
});;

Update:

Sometimes if you look for a button, jquery will return you the button, not the object so to edit or do some action you pass it as argument to the jquery constructor.

Here a little example. You are just looking for the button and jquery returns that button but if you need to apply some style,event, etc,etc, you would need to pass it as argument to the jquery contructor ($ or jQuery). And here another without the constructor that does not work

Upvotes: 0

eomeroff
eomeroff

Reputation: 9915

something is a jQuery object and there is no need to put it in brackets with dollar sign as this: $(something)

jQuery selectors return jQuery objects, which is case here $('#something').

Good naming practice would be to name something as $something, so you know that variable contains jQuery object.

Also good use of $(..) example, would be wrapping html as string to get jQuery object, like this:

$divObject = $('<div>Some text</div>');
$divObject.text(); // value is 'Some text'

Upvotes: 0

SLaks
SLaks

Reputation: 887275

$(...) returns a jQuery object.

If you put a jQuery object in a variable, the variable will still hold a jQuery object in it when you check on it later, just like anything else you might put in a variable.

No magical gremlins will come and get rid of the jQuery object behind your back.
(unless you accidentally put something else in the variable elsewhere)

Upvotes: 5

djechlin
djechlin

Reputation: 60748

This has nothing to do with jQuery. This is just a fundamental of Javascript.

var x = foo();
x.something();

Is of course the same as foo().something(). Go study programming or Javascript until this makes sense.

Upvotes: 1

Related Questions