Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create and modify the attributes of property in JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 122
    Comment on it

    This tutorial will help a user to learn how to create a property with specified attribute values or modify the attributes of a property that already exists in JavaScript


    1. Creating a property:

    1. // using Object.defineProperty() for creating a new property
    2.  
    3. var abc = {};
    4.  
    5. // define a property and assign its value and attributes
    6.  
    7.  
    8. Object.defineProperty(abc, "xyz",{ value : Hello World, writable: true, enumerable: false, configurable: true});
    9.  
    10. document.write(abc["xyz"]); // output: Hello World

    2. Modifying a property:

    1. <script>
    2.  
    3. // using Object.defineProperty() for creating a new property
    4.  
    5. var abc = {lm: Hello World};
    6.  
    7. document.write(abc["lm"]); // output: Hello World
    8.  
    9. // define a property and assign its value and attributes
    10.  
    11. Object.defineProperty(abc, "lm",{ value : 'Hello Everybody', writable: true, enumerable: false, configurable: true});
    12.  
    13. document.write(abc["lm"]); // output: Hello Everybody
    14. </script>

    3- Making a property read-only

    1. //To make a JavaScript execute in a strict mode we write use strict on top of the script file.
    2.  
    3. <script>
    4. "use strict"
    5.  
    6. var abc = {"xyz":562};
    7.  
    8. Object.defineProperty(abc, "xyz", { writable: false} );
    9.  
    10. abc["xyz"] = 420;
    11.  
    12. // if we use strict mode, then it's we get the following error
    13.  
    14. // TypeError: "xyz" is read-only
    15.  
    16. // if we use non strict mode we get the following output
    17.  
    18. document.write(abc["xyz"]); // output: 562
    19. </script>

    4- creating/modifying multiple properties of an object

    1. <script>
    2. var abc = {};
    3.  
    4. // here we will add 2 properties, with their attributes in the object abc
    5.  
    6. Object.defineProperties(
    7. abc,
    8. {
    9. prop1:{ value : 'Hello World', writable: true, enumerable: true, configurable: true},
    10. prop2:{ value : 'Thank you', writable: true, enumerable: true, configurable: true}
    11. }
    12. );
    13.  
    14. console.log(abc); // Object{ prop1: Hello World, prop2: Thank you }
    15.  
    16. </script>

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: