文章目录
  1. 1. JS 实现对象属性的get 和set方法 - 编程 - IT610.com

JS 实现对象属性的get 和set方法 - 编程 - IT610.com

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(){ // retur

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

}

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

文章目录
  1. 1. JS 实现对象属性的get 和set方法 - 编程 - IT610.com