首页 > 解决方案 > Javascript在不同场景中添加setter

问题描述

我正在学习 javascript(来自 php)并看到有多种创建类的方法。还了解了 get 和 set 之类的魔术方法,我想知道如何在不同的场景中创建它们(除了在使用 class 关键字创建类时这样做)。我还发布了在对象文字中执行 getter 和 setter 的方法,并且想知道是否有更简单的方法。这是代码

//-------------------------------------------------------------------
    //class
    class create{
        constructor(param1,param2){
            this.name = param1;
            this.name2 = param2;
        }

        fullname(){
            console.log('...');
        }

        set name3(enteredValue){
            this._name3 = enteredValue;
        }
        get name3(){
            return this._name3;
        }//This is how  it is done in class
    }
    var obj2 = new create('test','test');

//-------------------------------------------------------------------
    //object literal
    var objLit = {
        name: 'asas',
        name2: 'assad'
    }
    Object.defineProperty(objLit, 'name3', { 
        get : function(){
            return this._name3;
        },
        set : function(value){
            this._name3 = value;
        }
    }); //This is how it is done in obj literal / Is there other way to do it in object?
//-------------------------------------------------------------------

    //Factory Function
    function createObj(param1, param2){
        return{
            name1: param1,
            name2: param2,
            fullName: function(){
                console.log(this.name1+' '+this.name2);
            }
        }
    }
    var obj3 = createObj('Vukasin','Miljan');
    //How to add setter in this scenario?


//-------------------------------------------------------------------

    //Constructor function

    function createObj2(param1,param2){
        this.name1 = param1;
        this.name2 = param2;
    }
    var obj4 = new createObj2('..','..');
    //How to add setter in this scenario??

标签: javascriptclassoopsettergetter

解决方案


在对象中添加 getter/setter:

let objLit = {
    name: 'asas',
    name2: 'assad',
    get name3() {
        return this._name3
    },
    set name3(value) {
        this._name3 = value
    }
}

在工厂函数中:

function createObj(param1, param2) {
    return {
        set name1(value) {
            param1 = value
        },
        set name2(value) {
            param2 = value
        },
        get fullName() {
            return `${param1} {param2}`
        }
    }
}

推荐阅读