JS's accessor

Source: Internet
Author: User

1. Defining Get,set accessor properties in an object
<Script>        varTest={_name:"PMX", _age: -, _born:1990, get Name () {return "name is"+ This. _name; }, set name (value) { This. _name=value; }, get Born () {return  This. _born; }, set born (value) { This. _born=value; }, Get Age () {if( This. _age>  -){                    return NewDate (). getFullYear ()-  This. Born; }Else{                    return  This. _age; }}, set age (value) { This. _age=value;        }} console.log (Test.age); Test.age=  .; Console.log (Test.age);
</Script>
2. Adding an accessor to an object using DefineProperty
<Script>        varTest={_name:"PMX", _age: -, _born:1990} object.defineproperty (Test,"name", {get:function(){                return "name is"+ This. _name; }, set:function(value) { This. _name=value;        }        }); Object.defineproperties (test,{age:{get:function(){                    if( This. _age>  -){                            return NewDate (). getFullYear ()-  This. Born; }Else{                        return  This. _age; }}, set:function(value) { This. _age=value; }}, born:{get:function(){                    return  This. _born; }, set:function(value) { This. _born=value;         }            }        }); Console.log (Test.age); // -Test.age=  .; Console.log (Test.age); // -
</Script>

3. Adding accessors to a class
<Script>        functionTest (name,age) { This. _name=name;  This. _age=Age ; Object.defineproperty ( This,"name", {get:function(){                    return "name is"+ This. _name;        }            }); }        varTT= NewTest ('PMX', -); Console.log (tt.name);</Script>

JS's accessor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.