Javascript在不同情况下添加setter

时间:2018-11-22 14:37:10

标签: javascript class oop setter getter

我正在学习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??

1 个答案:

答案 0 :(得分:0)

在对象中添加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}`
        }
    }
}