this
当函数作为构造函数调用时对自身的引用,您可以使用立即调用的函数表达式 (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);
演示:http: //jsfiddle.net/fk4uydLc/1/
但是,您可以通过使用普通的旧 JavaScript 对象 (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);
演示:http: //jsfiddle.net/vmthv1dm/1/
如果您打算多次使用构造函数,那么@Quentin 提到的方法就是要走的路。
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);
演示:http: //jsfiddle.net/jsd3j46t/1/