本书中的命令模式是什么:学习JavaScript设计模式

时间:2018-12-13 05:42:07

标签: javascript

此问题来自函数闭包的使用,代码段如下:

(function() {
    var carManager = {
        // request information
        requestInfo: function(model, id) {
            return "The information for " + model + " with ID " + id + " is foobar";
        },

        // purchase the car
        buyVehicle: function(model, id) {
            return "You have successfully purchased Item " + id + ", a " + model;
        },

        // arrange a viewing
        arrangeViewing: function(model, id) {
            return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
        }
    };

})()

carManager.execute = function(name) {
    return carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1));
};

carManager.execute("arrangeViewing", "Ferrari", "14523");
carManager.execute("requestInfo", "Ford Mondeo", "54323");
carManager.execute("requestInfo", "Ford Escort", "34232");
carManager.execute("buyVehicle", "Ford Escort", "34232");

上面的代码很像使用函数闭包代替new的用法, 但是确实,当我在jsfiddle(https://jsfiddle.net/abramhum/1cLpuf8n/1/)中使用此示例时,它不起作用。 错误消息显示“ Uncaught ReferenceError:在window.onload上未定义carManager”。 关于在JavaScript中使用这种方式是否有任何定理或方法论。 有没有更多详细的材料来解释这一点。非常感谢。

1 个答案:

答案 0 :(得分:0)

重建后,工作示例如下:

(function() {
var carManager = {
    // request information
    requestInfo: function(model, id) {
        console.log("The information for " + model + " with ID " + id + " is foobar");
    },

    // purchase the car
    buyVehicle: function(model, id) {
        console.log("You have successfully purchased Item " + id + ", a " + model);
    },

    // arrange a viewing
    arrangeViewing: function(model, id) {
        console.log("You have successfully booked a viewing of " + model + " ( " + id + " ) ");
    }
};
carManager.execute = function(name) {
    return carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1));
};

carManager.execute("arrangeViewing", "Ferrari", "14523");
carManager.execute("requestInfo", "Ford Mondeo", "54323");
carManager.execute("requestInfo", "Ford Escort", "34232");
carManager.execute("buyVehicle", "Ford Escort", "34232");
})()