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

alert(boxArea.width);

Good day. Why does this return an undefined value?

2
  • 2
    Read up the on javascript's module pattern. It explains how your width variable is private to the boxArea object. Commented Mar 22, 2012 at 23:33
  • will work with "= new function" Commented Mar 22, 2012 at 23:36

2 Answers 2

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);​
Sign up to request clarification or add additional context in comments.

7 Comments

okay so the new keyword makes a new object. but isn't it that functions are also object?
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).
Can I say that var person = {}; is same as var person=new object();
Yes, that is called "object literal" syntax.
and what is the equivalent syntax for "new function()"?
|
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};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.