简体   繁体   中英

Javascript object creation using functions

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

alert(boxArea.width);

Good day. Why does this return an undefined value?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM