-1

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();
});
2
  • 2
    Is that the actual code? 'cause all that's going to do is throw an exception when the ready handler runs. MyObject is undefined after that first statement. Commented Jan 18, 2015 at 13:17
  • I found this code in the project. Commented Jan 18, 2015 at 13:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.