this
references to itself when the function is invoked as a constructor which you can do by using an immediately invoked function expression (IIFE).
var cooking = (function () {
return new function () {
this.dessert = "Ice Cream";
this.numberOfPortions = 20;
this.doubleLunch = function () {
this.numberOfPortions = 40;
document.write(this.numberOfPortions);
};
}
})();
document.write(cooking.dessert);
DEMO: http://jsfiddle.net/fk4uydLc/1/
However, you can achieve the same result by using a plain old JavaScript object (POJO).
var cooking = (function () {
var obj = {};
obj.dessert = "Ice Cream";
obj.numberOfPortions = 20;
obj.doubleLunch = function () {
obj.numberOfPortions = 40;
document.write(obj.numberOfPortions);
};
return obj;
})();
document.write(cooking.dessert);
DEMO: http://jsfiddle.net/vmthv1dm/1/
If you plan on using the constructor multiple times then the approach @Quentin mentioned is the way to go.
function Cooking() {
this.dessert = "Ice Cream";
this.numberOfPortions = 20;
this.doubleLunch = function () {
this.numberOfPortions = 40;
document.write(this.numberOfPortions);
};
}
var cooking = new Cooking();
document.write(cooking.dessert);
DEMO: http://jsfiddle.net/jsd3j46t/1/