美文网首页
探索es6中的Proxy对象

探索es6中的Proxy对象

作者: 南方四季 | 来源:发表于2018-06-15 09:16 被阅读0次

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

    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() // 将抛出错误 

    相关文章

      网友评论

          本文标题:探索es6中的Proxy对象

          本文链接:https://www.haomeiwen.com/subject/nreibxtx.html