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()+"被获取!")
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM