Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Creating objects in JavaScript...

    • 0
    • 4
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 163
    Comment on it

    Hey guys in this blog we are going to look at creating objects in JS, having properties and methods attached to them :

    var car = new Object();//Creating a brand new object...
    //Adding properties to the newly created object ...
    car.Wheels = 4 ;
    car.Mileage = 20.4 ;
    car.Brand = "Maruti";
    car.Music = "false"
    //In order to attach a simple method to a js object we first need to define that method as : 
    function setMusic( isMusicOn ){
        if(isMusicOn){
            this.music = true ;
        }else{
            this.music = false ;
        }
    }
    //Now that we've defined the method we need to attach it to our object...
    car.setMusic = setMusic;
    //Now we can call the method...
    car.setMusic(true);
    //So since basic object has been created let's check its properties and method
    console.log("No of wheels : " + car.Wheels);
    console.log("Mileage : "+car.Mileage);
    console.log("Brand : " + car.Brand);
    console.log("Music : " + car.Music);
    
    // Sure the above 'car' object is fine on its own but JS provides a short hand notation to create an object
    var train = {Capacity: 500, Coaches: 15, Type : "Steam"};
    console.log("Capacity of train : " + train.Capacity);
    console.log("No of coaches" + train.Coaches);
    console.log("Engine Type : " + train.Type);
    
    

    The given 'train' object creation shows a short hand notation to create objects in javascript,  using set of key-value pairs as properties and value.

    Hope it's informative . Cheers!!!

 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: