user5372
user5372

Reputation: 175

jQuery - Object declaration

I found the following jquery code pattern. I think it was chosen to structure the code in a better way. I was wondering because the object declaration has no 'var' or something. Is the code right?

JS

MyObject = (function() {


 return function() {
    alert("object created");
 };
})();

$(function() {
    new MyObject();
});

Upvotes: -1

Views: 76

Answers (2)

JLRishe
JLRishe

Reputation: 101680

Based on your comment, it sounds like that is the actual code you have and not a paraphrased version of it, so that's just some bogus code.

  1. You can create a variable and assign a value to it without using var and it will be treated as a global variable, but this is considered a bad practice and forbidden in strict mode.
  2. The first statement is an IIFE, but it doesn't return anything, so MyObject is undefined. So when new MyObject(); eventually runs, it will just throw an error and halt the execution of the ready handler.

It looks like the person who wrote that code may have been trying to do this, but was making an attempt to be clever:

var MyObject = function() {
    alert("Object created");
};

$(function() {
    new MyObject();
});

Here, MyObject is a function that shows an alert. The jQuery ready handler invokes that function as a constructor, which causes the code inside the function to run (showing an alert), and creating a new object. However, this object is not used or assigned anywhere, so it just gets garbage collected after some period of time.

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Using variable without var keyword is set to global scope. So, MyObject is equivalent to window.MyObject and you can it elsewhere in your script.

Upvotes: 0

Related Questions