`

getter 方法与 getter属性

 
阅读更多

对象的 getter 属性

    getter 方法模板:

        this.property =
        {
            valueOf : function(){return ...},
            toString : function(){return ...}
        }
        

 


    例子:

function Student1(name, age, gender)
        {
            this.name = name;
            this.age = age;
            this.gender = gender;
           
            // getter 方法的形式获得信息
            this.getInfo = function ()
            {
                return "Hello ! My name is " + name
                       + "\n I am " + age + " years old !"
                       + "\nI'a " + gender;
            }
        }

        function Student2(name, age, gender)
        {
            this.name = name;
            this.age = age;
            this.gender = gender;
           
            //定义成属性  模拟getter方法  来获取信息
            this.info =
            {
                valueOf:function()
                {
                    return "Hello ! My name is " + name
                       + "\n I am " + age + " years old !"
                       + "\nI'a " + gender;
                },
                toString:function()
                {   
                    return "Hello ! My name is " + name
                       + "\n I am " + age + " years old !"
                       + "\nI'a " + gender;
                }
            }
        }

        var stu1 = new Student1("xiaoming", 22, "male");
        var stu2 = new Student2("xiaofang", 21, "famale");

        alert(stu1.getInfo()); // getter 方法
        alert(stu2.info); // 对象的 getter 属性

 

       
对象的setter属性目前只能由 setXxx 方法来实现,目前的 ECMA Script V3 不支持
setter 属性。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics