JS 实现对象属性的get 和set方法

/*1.自定义用户类  name:用户名称,age:年龄*/
function User(name,age){
    this.Name=name;
    this.Age =age;
}
/*2.为Age 属性添加get和set方法,方法1*/
//    Field.prototype = {
//        get Age(){
//            return this._Age;
//        },
//        set Age(age){
//            this._Age = age;
//            ShowSetInfo(this);
//        }
//    };
/*2.为Age属性添加get和set方法,方法2*/
    User.prototype.__defineGetter__("Age", function () {
        ShowGetInfo("Age");
        return this._Age;
    });
    User.prototype.__defineSetter__("Age", function (val) {
        this._Age = val;
        ShowSetInfo("Age");
    });

/*3.进行属性的赋值与获取测试*/
var newuser = new User("markeluo",23);
newuser.Age=15;
var agevalue= newuser.Age;

function ShowSetInfo(_obj){
    alert(_obj.toString()+"被赋值!")
}
function ShowGetInfo(_obj){
    alert(_obj.toString()+"被获取!")
}
原文地址:https://www.cnblogs.com/luowanli/p/2619594.html