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
    • 121
    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:

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

    2. Modifying a property:

    <script>
    
    // using Object.defineProperty() for creating a new property
    
    var abc = {lm: Hello World};
    
    document.write(abc["lm"]);      // output: Hello World
    
    // define a property and assign its value and attributes
    
    Object.defineProperty(abc, "lm",{ value : 'Hello Everybody', writable: true, enumerable: false, configurable: true});
    
    document.write(abc["lm"]);            // output: Hello Everybody
    </script>
    

    3- Making a property read-only

    //To make a JavaScript execute in a strict mode we write use strict on top of the script file.
    
    <script>
     "use strict"
    
    var abc = {"xyz":562};
    
    Object.defineProperty(abc, "xyz", { writable: false} );
    
    abc["xyz"] = 420;                   
    
    // if we use strict mode, then it's we get the following error
    
    // TypeError: "xyz" is read-only 
    
    // if we use non strict mode we get the following output
    
    document.write(abc["xyz"]);         // output: 562        
    </script>
    

    4- creating/modifying multiple properties of an object

    <script>
    var abc = {};
    
    // here we will add 2 properties, with their attributes in the object abc
    
    Object.defineProperties(
        abc,
        {
            prop1:{ value : 'Hello World', writable: true, enumerable: true, configurable: true},
            prop2:{ value : 'Thank you', writable: true, enumerable: true, configurable: true}
        }
    );
    
    console.log(abc);               // Object{ prop1: Hello World, prop2: Thank you }
    
    </script>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: