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