1)Javascript设计模式:Module模式

时间:2023-03-09 07:41:51
1)Javascript设计模式:Module模式

最简单的创建对象方法


function User(name) {
this.name = name || ''
} User.prototype.say = function() {
console.log('Hi, My name is ' + this.name);
} var u = new User('tom')

缺点:此种方法无法实现私有成员变量的隐藏

私有模式

var User = (function() {
var sayCount = 0;
var _say = function() {
sayCount ++;
} return {
say: function() {
_say()
console.log('')
}
}
})();
var User = (function() {
var sayCount = 0;
var _say = function() {
sayCount ++;
} return {
say: function() {
_say()
console.log('')
}, run: function() {
// 可以调用say方法吗?
// this.say(); 好像不可以,这里的this是context window对象。
// 这种模式是有缺点的,无法在这里调用say方法,只能这样User.say() // 如果私有方法出了bug,由于无法从外部打补丁,也无法对私有方法进行扩展
}
}
})();
// Revealing Module
var User = (function() {
var sayCount = 0;
var _say = function() {
sayCount ++;
} function publicSay() {
_say()
console.log('')
publicRun()
} function publicRun() { } return {
say: publicSay,
run: publicRun
}
})();