1

I'm wondering what the difference, or if any, the following JS is for building up an object. Is it a style thing/standards thing? If so, which is most common?

Example 1:

var MyNamspace = {
  options: { test: 10 },
  someFunction: function() { alert("Hello"); }
}

Example 2:

var MyNamespace = {};
MyNamespace.options = { test: 10 };
MyNamespace.someFunction = function() { alert("Hello"); }

Thanks.

3 Answers 3

4

There is no significant difference between the two (although the second is probably marginally slower).

The first example is more usual.

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

Comments

2

The first MyNamspace is missing an "e", else there is no functional difference.

The second pattern is used when there is already an object with properties (like someFunc.prototype) which you want to extend, but you'd need to leave the overwriting part (MyNamespace = {};) away.

Comments

1

The second option modifies an existing type, so while equal, the second is modifying the signature of an existing type, just like you could do: MyClass.prototype.someFunction = function() { }

This is where JavaScript can be conveniently flexible.

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.