JavaScript Object Accessor Properties

Source: Internet
Author: User

  Object accessors are setters and getter, and their role is to

      1. Provides another way to get or set the property value of an object,
      2. And in the acquisition and setting, you can use a certain other operation.

Look at the following code:

<script>var person = {_name: "abc",   //Note here _name has an underscore};object.defineproperty (person, "name", {/// Note that the second argument is not preceded by an underscore, so _name and name are two different properties Set:function (value) {this._name = "new name" + value;   Note here is the assignment to the _name property},get:function () {return "This is name ' Get By Function:" + this._name;  Note that this is the return string plus the value of _name}});//Here, the person has two properties: _name and the name attribute//Get _name Property directly Console.log (Person._name);  abc//gets the value of _name indirectly through the Name property, because the Getter accessor property (method) Console.log (person.name) of the Name property is executed;   This is the name of the Get by function:abc//directly modifying the _name property Person._name = "xyz"; Console.log (person._name);  xyz//modifies the Name property, but the setter accessor property (method) of the Name property acts on the _name property Person.name = "WTF"; The string is prefixed with the new name and then assigned to _nameconsole.log (person._name);  New name Wtfconsole.log (person.name);//this is name get by function:new name wtf</script>

  

JavaScript Object Accessor Properties

Related Article

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.