前言

首先出道面试上机题简化版(来自喜马拉雅Fm),侵删。

        ****
        你需要在这里完成People的构造函数
        ****
        //从而会按照期望执行下面的代码
        var man = new People("小明");
        var women = new People("小红")
        console.log(man.name)      // 期望为       小明
        man.name = "小刚"          // 期望为        warn:不允许通过赋值运算符
        console.log(man.name)     // 期望为       小明
        console.log(women.name)   // 期望为       小红
        women.setName("小黄")
        console.log(women.name)   // 期望为       小黄

clipboard.png

我的方案

Object.defineProperty

 var People = function (name){
            this._name = name;
            Object.defineProperty(this,"name",{
                get:function(){
                    return this._name
                },
                set:function(name){
                    console.warn('不允许通过赋值运算符')
                }
            })
            this.setName = function(name){
                this._name = name;
            }
        }

Proxy

var createPeople = function(name){
            var obj = new Object();
            obj._name = name;
            obj.setName =  function(name){
                this._name = name;
            }
            return obj
        }
        var People = function (name){
            return new Proxy(createPeople(name), {
            get: function (target, key, receiver) {
                if(key === 'name'){
                    return target['_name']
                }
                return target[key];
            },
            set:function(target,key,value,receiver){
                if(key === '_name'){
                    target._name = value
                    return 
                }
                console.warn('不允许通过赋值运算符')
            }
        });
        }

Class

class People{
             constructor(name){
                 this._name = name;
             }
             get name(){
                 return this._name;
             }
             set name(name){
                console.warn('不允许通过赋值运算符')
             }
             setName(name){
                 this._name = name;
             }
        }

小结

我把自己的代码放出来,抛砖引玉,也希望大家可以 review我的代码,指出不足之处和可优化之处。

ThenMorning
190 声望18 粉丝

但行好事,莫问前程.