var boxArea = function() {
this.width=2;
};
alert(boxArea.width);
Good day. Why does this return an undefined value?
mechanical_meat
171k25 gold badges238 silver badges231 bronze badges
-
2Read up the on javascript's module pattern. It explains how your width variable is private to the boxArea object.Straseus– Straseus2012年03月22日 23:33:50 +00:00Commented Mar 22, 2012 at 23:33
-
will work with "= new function"qux– qux2012年03月22日 23:36:01 +00:00Commented Mar 22, 2012 at 23:36
2 Answers 2
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
DevX
okay so the new keyword makes a new object. but isn't it that functions are also object?
Timeout
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).
DevX
Can I say that var person = {}; is same as var person=new object();
Timeout
Yes, that is called "object literal" syntax.
DevX
and what is the equivalent syntax for "new function()"?
|
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};
answered Mar 23, 2012 at 3:04
RobG
148k32 gold badges180 silver badges216 bronze badges
Comments
lang-js