0

我读过我们可以将匿名函数作为变量调用。但是我正在尝试这样做,除此之外,我还想访问它的属性和方法。这是我的代码

var cooking = function(){
        this.dessert = "Ice Cream";
        this.numberOfPortions = 20;
        this.doubleLunch = function(){this.numberOfPortions = 40;
            document.write(this.numberOfPortions);};
        };

document.write(cooking.dessert);

但我什么也得不到。你能说我在做什么错吗?谢谢

4

2 回答 2

1

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/

于 2015-10-07T23:03:51.983 回答
1

cooking是一个函数。当您调用它时,它定义了许多属性this

该结构意味着它旨在用作构造函数,因此您将使用new关键字创建它的实例。

然后您可以与实例进行交互。

var meal = new cooking();
document.write(meal.dessert);

注意:约定规定构造函数(并且只有构造函数)应该以首字母大写开头,因此您应该将其重命名为 Cooking。

于 2015-10-07T22:51:54.420 回答