Search code examples
javascriptobject-type

JavaScript: The Good Parts : class-free objects


In JavaScript: The Good Parts, Chapter 3, Objects

Objects in JavaScript are class-free. There is no constraint on the names of new properties or on the values of properties.

The statement

There is no constraint on the names of new properties

Why is it the part of class-free definition? Isn't common with all programming language irrespective of whether the language is class-free or non class-free?

I understand below statement makes sense for class-free object.

or on the values of properties.


Solution

  • In many programming languages, objects are an instance of a particular class. The properties and types of those properties are defined in the code that defines the class. Objects that are instances of those classes can be trusted to have values of the defined type, or null, for the property names that were defined in that class. You can't just add a new property to your object and you can only set the properties to values of a particular type. You can get around this, somewhat, by extend the classes in those languages but that requires creating an additional class. In PHP, C# or Java, if you wanted to create an object of type Car with a public property to set and get the color, you would have to create a class.

    In JavaScript, you can add new properties to any object, with any name, and any value, at any time. You do not have to create a class and then create an object which is an instance of that class.

    // object notation
    var myCar = new Object();
    myCar.color = 'red';
    // JSON notation
    var myOtherCar = { color: 'red' };
    console.log( 'myOtherCar.color: ' + myOtherCar.color );
    // see how we initialized the value as a string and then changed it to an array of ints?
    myOtherCar.color = [1,2,3,4];
    console.log( 'myOtherCar.color: ' + myOtherCar.color );
    // see how we created a new property that wasn't declared in a class structure?
    myOtherCar.gasTank = .5;
    console.log( 'myOtherCar.gasTank: ' + myOtherCar.gasTank );
    // Is the gas tank half full or half empty?