module模式,是建立在对象字面量上面的,最基本的对象字面量的形式是:
var Car = {};
基于对象字面量的module模式的实现方式:
var Car = { color: ‘white‘, getCarPrice: function () { }, getCarColor: function () { console.log(this.color); } }; Car.getCarColor();
再做深入的理解,在module模式上实现private和public的方法和变量的方式。
var testModule = function(){ var privateValue = 1; var publicValue = 2; var privateMethod = function(){}; var publicMethod = function(){ console.log(privateValue); }; var service = { publicMethod:publicMethod, publicValue:publicValue }; return service; }; testModule().publicMethod();//1 testModule().privateMethod();//undefined is not a function testModule().privateValue;//no error , just console nothing
继续修改一下
var testModule = (function(){ var privateValue = 1; var publicValue = 2; var privateMethod = function(){}; var publicMethod = function(){ console.log(publicValue); }; var service = { publicMethod:publicMethod, publicValue:publicValue }; return service; })(); testModule.publicMethod();//2 testModule.publicValue = 3; testModule.publicMethod();//2 无法修改,
如果想要修改内部变量,只能通过提供外部方法去修改
var testModule = (function(){ var privateValue = 1; var publicValue = 2; var privateMethod = function(){}; var publicMethod = function(){ console.log(publicValue); }; var setPublicValue = function(value){ publicValue = value; }; var service = { publicMethod:publicMethod, publicValue:publicValue, setPublicValue:setPublicValue }; return service; })(); testModule.publicMethod();//2 testModule.setPublicValue(4); testModule.publicMethod();//4
时间: 2024-10-06 19:25:01