JavaScript簡単にget、setメソッドを修正して双方向バインドを実現


//  ES5 get、set  
var obj = {
    name:'Hello',
    height:150,
    get age(){
        console.log('   age      ');
        return new Date().getFullYear() - 1988;
    },
    set age(val){
        console.log('   age      ');
        console.log('age newVal:'+val);
    }
}

//       
    function defineProperty(obj, attr){
        //    Object.defineProperty
        Object.defineProperty(obj, attr, {
            get: function () {
                return val;
            },
            set: function (newValue) {
                document.getElementById("input").value = newValue;
                document.getElementById("show").innerHTML = newValue;
            }
        });
    }
 
    var obj = {};
    defineProperty(obj, "txt");
    document.getElementById("input").addEventListener("keyup", function(e){
        obj.txt = e.target.value;
    });
    obj.txt = 200;