一、构造函数实现私有变量
特权方法定义在this上,用new实例化后,就可以访问到在new的过程中隐式调用构造函数时产生的私有变量(不知道new过程的点这里)
function Person(name) {
this.getName = function () {
return name
}
this.setName = function (value) {
name = value
}
}
let person = new Person('Henry')
console.log(person.getName()) //Henry
person.setName('Jamie')
console.log(person.getName()) //Jamie
这个方法的缺点是每个实例都会重新创建一遍新方法
二、原型模式实现静态私有变量
立即执行函数内部挂载一个构造函数到外部变量上,然后把特权方法定义在够着函数的原型上,实例化后可通过原型链访问到特权方法
let Person;
(function () {
let name = ''
Person = function (value) {
name = value
}
Person.prototype.getName = function () {
return name
}
Person.prototype.setName = function (value) {
name = value
}
})()
let person1 = new Person('Henry')
console.log(person1.getName()) //Henry
person1.setName('Jamie')
console.log(person1.getName()) //Jamie
let person2 = new Person('Tony')
console.log(person1.getName()) //Tony
console.log(person2.getName()) //Tony
这个方法是name变成了静态私有变量,可供所有实例使用
三、模块模式(单例+IIFE实现)
立即执行函数内部返回拥有特权方法的对象
let app = function () {
let components = []
return {
getComponentCount() {
return components.length
},
registerComponent(component) {
if (typeof components === 'object') {
components.push(component)
}
}
}
}()
app.registerComponent({ name: 'nav' })
console.log(app.getComponentCount()) //1
还可以通过在返回新对象之前对其进行增强,这种方式适合要返回的单例对象需要是某个特定类型的实例,同时还必须给它添加额外属性或方法的场景
function BaseComponent(value = '') {
this.name = value
}
let application = function () {
let components = []
//初始化
components.push(new BaseComponent())
//创建特定类型的实例
let app = new BaseComponent()
app.getComponentCount = function () {
return components.length
}
app.registerComponent = function (component) {
if (typeof components === 'object') {
components.push(component)
}
}
return app
}()
application.registerComponent({ name: 'nav' })
console.log(application.getComponentCount()) //2
console.log(application instanceof BaseComponent) //true
这样就可以返回一个能够被 instanceof 操作符确定类型的对象,同时这个对象还有着对应的私有变量和操作私有变量的特权方法