DevX
DevX

Reputation: 99

Javascript object creation using functions

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

alert(boxArea.width);

Good day. Why does this return an undefined value?

Upvotes: 0

Views: 102

Answers (2)

RobG
RobG

Reputation: 147363

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};

Upvotes: 0

Timeout
Timeout

Reputation: 7909

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);​

Upvotes: 3

Related Questions