探索es6中的Proxy对象

设置一个内部属性 不能被外部使用

const handel4={

    checkProp(property,type){

        if(property[0]==='_'){

            throw new Error(`有句mmp 不知当讲不当讲:不允许${type}这个${property}私有属性!!!!!`)

        }

    },

    get(target,property){

        this.checkProp(property,"get")

        return target[property]

    },

    set(target,property,value){

        this.checkProp(property,"set")

        return target[property]=value

    }

}

class Car{

    constructor(name){

        this.name=name

        return new Proxy(this,handel4)

    }

    static sayName(){ // 只能被Car 调用

        console.log(this.name)

    }

    _goRight(){

        console.log('ooo')

    }

    goLeft(){

        console.log(this.name)

    }

}

let c2 = new Car("lp") // 创建实例

Car.sayName() //调用静态方法 只能被类调用

c2.goLeft() //正常调用

c2._goRight() // 将抛出错误 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容