Java Reference
In-Depth Information
To create an instance of the Dice object, invoke the constructor function using the new
var red = new Dice();
<< {"roll": function () {
return Math.floor(this.sides * Math.random() + 1)
}, "sides": 6}
The function returned an object that was assigned to the variable red , which is said to be
an instance of the Dice constructor function. We can confirm this using the instanceof
red instanceof Dice
<< true
This means that it will have a sides property and roll() method:
<< 6
<< 4
Warning: Use new
Make sure that you use the new operator when employing a constructor
function to instantiate a new object. Otherwise, you'll actually just call the
function itself, and will assign the variable to the return value of the func-
tion (which is usually undefined):
var yellow = Dice();
<< undefined
<< Error: "yellow is undefined"
Search WWH ::

Custom Search