0
var boxArea = function() {
    this.width=2;
};

alert(boxArea.width);

Good day. Why does this return an undefined value?

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
DevX
  • 99
  • 5
  • 2
    Read up the on javascript's [module pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth). It explains how your width variable is private to the boxArea object. – Straseus Mar 22 '12 at 23:33
  • will work with "= new function" – qux Mar 22 '12 at 23:36

2 Answers2

3

Because you created a function with that syntax. You have to add the "new" keyword in front of the function() to make it the equivalent of a class.

jsFiddle Demo: http://jsfiddle.net/dfUQu/

var boxArea = new function() {
    this.width=2;
};

alert(boxArea.width);​
Timeout
  • 7,759
  • 26
  • 38
  • okay so the new keyword makes a new object. but isn't it that functions are also object? – DevX Mar 22 '12 at 23:55
  • 1
    They are similar in syntax but designed for different purposes. A function is just meant to be called in order to perform some work. Once it exits anything defined inside is now out of scope and discarded. A class is meant to be *instantiated* and *reused*. The *new* keyword creates an *instance* of any user defined (or build in object, like Date() for example). – Timeout Mar 23 '12 at 00:06
  • Can I say that var person = {}; is same as var person=new object(); – DevX Mar 23 '12 at 00:15
  • Yes, that is called "object literal" syntax. – Timeout Mar 23 '12 at 00:17
  • and what is the equivalent syntax for "new function()"? – DevX Mar 23 '12 at 00:19
  • In object literal? var boxArea = { width: 2 }; – Timeout Mar 23 '12 at 00:23
  • how about in terms of function? – DevX Mar 23 '12 at 00:52
0

The classic way to create a javascript constructor is using a declared function:

function BoxArea(width) {
  this.width = width;
}

By convention, constructors have names starting with a capital letter. Then you create an instance:

var ba = new BoxArea(2);

alert(ba.width); // 2

For such a simple object you could just do:

var ba = {width: 2};
RobG
  • 142,382
  • 31
  • 172
  • 209