JS实现私有变量

一、构造函数实现私有变量

特权方法定义在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 操作符确定类型的对象,同时这个对象还有着对应的私有变量和操作私有变量的特权方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值