Welcome to the Javascript Objects Homepage, Guest!


Javascript | The attribute mapping of real life




Objects

A person, place, or a thing can all be objects. In rea life, I am an object. I possess the attributes of a first name, last name, age, degree, and many more attributes. Additional objects could be a motorcycle, a car, or Donald Trump. A motorcycle has properties or attributes like weight, color, and gear ratio, but contains many methods associated with the objects like start, stop, or honk the horn. Dates, Maths, Regex, Arrays, Functions, and Objects are always defined as objects within Javascript. Booleans, Numbers, and Strings can be objects if defined using the new keyword. Javascript has 5 different data types that are considered primitive data types. Primitive data types are assigned primitive values. A primitive value is a value that has no property or methods; string, number, boolean, null, and undefined. Primitives are immutable, meaning they are usually hard coded by a programmer and cannot be changed unless programmatically.



All motorcycles will have the same properties, but the property values differ from motorcycle to motorcycle. All motorcycles have the same methods associated with them, but the methods will be performed or executed at different times or intervals. Remember, Javascript variables are containers for data types associated with Javascript.

var motorcycle = "Honda Shadow";

The code above declares a variable named motorcycle with a simple string value assigned; Honda Shadow.

Objects are treated as variables too, but objects can and will contain much more descriptive information related to the object that is being created.

var motorcycle = { type:"Honda", model:"Shadow", color:"Candy Apple Red", motorSize: 750};

The code above declares a motorcycle object and assigns values for type, model, color, and motorSize. The values are written as name value pairs; name:value. The name and value are separated by a colon between the two. Javascript objects can be seen as containers for named values. The name value pairs are considered to be properties of the object. Objects written as a name value pair are similar to hash maps in Java, hash tables in C, Dictionaries in Python, Associative arrays in PHP, or hashes in Ruby or Perl. The similarities are with the way you code the objects, and not in the way the language uses the data. A dictionary in Python might access, delete, modify, or copy quicker than a hash in Ruby, but a has in Ruby might be faster at backing up the information than a diction in Python. Perhaps, your company wants to ensure their data is backed up every night within a short window, and Ruby seems to meet your qualifications. Then, you become an expert on Ruby overnight. You can definitely define and create your own objects within Javascript using a object literal, the keyword new, or define an object constructor to construct objects dynamically for you. The newest update to Javascipt allows the programmer to create objects using the syntax: Object.create();. The code below shows how to create an object using an object literal.

var person = {firstName:"James", lastName:"Patterson", age:30, hairColor:"Brown", sex:"Male", race:"Native American"};

Property:Property Value
firstName:James
lastName:Patterson
age:30
hairColor:Brown
sex:Male
race:Native American

Property Attributes

All properties have a name and a value associated with the name. The value is considered one of the property's attributes. Additional attributes include enumerable, configurable, and writable. Those attributes define just how the property can be accessed; readable, writable, etc. Javascript allows all attributes to be read, but only the value attribute can be changed if the property is writable. The newest version of Javascript has methods for getting and setting any property attribute.

You can use the Javascript keyword new to create an object:

var person = new Object();
person.firstName = "James";
person.lastName = "Patterson";
person.age = 30;
person.hairColor = "Brown"; person.sex = "Male"; person.race = "Native American";


The object literal method would be the preferred method of choice by most programmers. Due to the environment that Javascript will probably be running in, you will want Javascript to run as fast as possible without slowing down the browser or web application in any way.

If you find yourself needing to create a lot of objects within an application, but do not have the time to hard code each individual object yourself. You need to start using an object constructor. The examples above only create one single object, but you sometimes need an object type that can be used to create many different objects. Object Constructors formally create your objects for you while requiring you to hard code the required information for the object.

function personHired(first, last, age, degree){
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.degree = collegeDegree;
}

The way you would use the obect constructor: var mySelf = new personHired("James", "Patterson", 30, "B.S. Computer Science");

The above constructor requires four different parameters to work properly; first, last, age, and degree. Once you code the constructor, you can then continue to create new objects of the same type; person, car, motorcycle, and more.

Do not let the this keyword scare you away or confuse you in any way. The this keyword is used within the constructor to refer to the object currently being created. So, as you pass the parameters into the constructor, the constructor will then create a new object based on the properties you've supplied to it using the parameters. This just attaches the values to the properties of the current object being created by the constructor.

Javascript does have built-in constructors available to use at will:

Object object
var a = new Object();

String object
var b = new String();

Number object
var c = new Number();

Boolean object
var d = new Boolean();

Array object
var e = new Array();

Regular Expression object
var f = new RegExp();

Function object
var g = new Function();

Date object
var h = new Date();



The Math() object is not apart of this list due to Math being a global object. The new keyword cannot be used with global objects. Honestly, there is no reason to code any of these data types with the new keyword, and using the new keyword will slow your application down due to increased execution time. Below is the way you should define each type of data type:

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    
      var obj = {};
      var str = "";
      var num = 5;
      var bool = true;
      var array = [];
      var regex = /()/;
      var func = function(){};

      document.getElementById("tutorial").innerHTML =
      "obj: " + typeof obj + "<br>" +
      "str: " + typeof str + "<br>" +
      "num: " + typeof num + "<br>" +
      "bool: " + typeof bool + "<br>" +
      "array: " + typeof array + "<br>" +
      "regex: " + typeof regex + "<br>" +
      "func: " + typeof func + "<br>";
      
    </script>

  </body>
</html>



String, Number, and Boolean objects should be created as primitives, and not declared as objects. Primitives could yield unexpected results while creating via Object creation.

Objects are quite mutable within Javascript. They are addressed by reference, and not by value. If we use the person object from above, and write var x = person;. The object x is not a copy of person, but the object x will be person. After the assignment, x and person will become the same object, and any change to x will change person and vice versa.

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
      var person = {firstName:"James", lastName:"Patterson", age:50}

      var temp = person;
      temp.age = 30;

      document.getElementById("tutorial").innerHTML =
      person.firstName + " is " + person.age + " years old.";
    </script>

  </body>
</html>



Output: James is 30 years old.




Methods

The actions that are or can be performed on objects are known as methods inside Javascript. Methods are stored in the properties as a function definition. Object properties can be primitive values, other objects, and functions. An object method is an object property containing a function definition. Let us build on the example from above:

var person = {firstName:"James", lastName:"Patterson", age:30, hairColor:"Brown", sex:"Male", race:"Native American", myFunc(){return this.firstName + " " + this.lastName;};

Property:Property Value
firstName:James
lastName:Patterson
age:30
hairColor:Brown
sex:Male
race:Native American
fullName:myFunc(){return this.firstName + " " + this.lastName;}

Javascript objects are just containers for named values called properties or methods. The object definition is a variable declaration of sorts. var person = {firstName:"James", lastName:"Patterson"}; is an object declaration with two properties; firstName and lastName. Spaces and line breaks are irrelevant when it comes to object definition, and the definition can span multiple lines.

var person = {
    firstName: "James",
    lastName: "Patterson
};




Accessing Object Methods

To access an objects method, you can use this syntax: nameOfObject.nameOfMethod(). Let us use the same example as the code from before. We will create another property named fullName, but make this property a function to perform concatenation on our first and last names.

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    var person = {
        firstName: "James",
        lastName : "Patterson",
        age       :  30,
          fullName : function() {
       return this.firstName + " " + this.lastName;
    }
    };
    
    var a = person.age;
    
    document.getElementById("tutorial").innerHTML =
    person.fullName() + " is " + a + " years old.";
    </script>

  </body>
</html>



Remember: if you call the fullName method without the use of the two (), the function definition will be returned instead of the string values you wish to receive. A method is a function definition stored as a property value. Avoid declaring a object as type String, Number, or Boolean unless you fully understand what you are doing. The declaration can complicate code, and slow down the execution speed within the browser. The idea behind Javascript was to bring OOP principles into the realm of web development and design in order to offer more readibly available dynamic results. If your web site takes longer than a few seconds to load, the user might become skeptical, and wish to return to a previous site to continue searching for their query information.




Adding New Methods

Adding additional methods to an object is accomplished within the constructor function:

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>
    <p id="tutorial2"></p>

    <script>
    
      function person(firstName,lastName,age) {
          this.firstName = firstName;
          this.lastName = lastName;
          this.age = age;
          this.changeAge = function (a) {
              this.age = a;
          }
      }

      var myMother = new person("Jill","Hardin", 48);
      
      document.getElementById("tutorial").innerHTML =
      "My mother's name is " + myMother.firstName + " " + myMother.lastName + ".";
      
      myMother.changeAge(52);
            
      document.getElementById("tutorial2").innerHTML =
      "She is  " + myMother.age + " years old.";
      
    </script>
  </body>
</html>



Using myMother.changeAge is effectively replacing the keyword this in the code above, and Javascript knows which person you are referring to.




Built-In Functions

Built-In Javascript methods are great, because a lot of simple tasks you might end up needing to use will be solved easily using a Javascript built-in method. The reason the built-in methods become built-in is because they have shown to increase productivity one way or another. The example below is a short and simple way of using one of the built-in Javascript methods available:

var helloWorld = "Hello World!";

var newHelloWorld = hellowWorld.toUpperCase();

Output: HELLO WORLD!




Number Methods

The Number object contains only the default methods that are part of every object's definition.

Method Description
constructor() Returns the function that created this object's instance. By default this is the Number object.
toExponential() Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocaleString() Returns a string value version of the current number in a format that may vary according to a browser's locale settings.
toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
toString() Returns the string representation of the number's value.
valueOf() Returns the number's value.

Boolean Methods

Method Description
toSource() Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
toString() Returns a string of either "true" or "false" depending upon the value of the object.
valueOf() Returns the primitive value of the Boolean object.

String Methods

Method Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
length() Returns the length of the string.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search() Executes the search for a match between a regular expression and a specified string.
slice() Extracts a section of a string and returns a new string.
split() Splits a String object into an array of strings by separating the string into substrings.
substr() Returns the characters in a string beginning at the specified location through the specified number of characters.
substring() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale.
toLowerCase() Returns the calling string value converted to lower case.
toString() Returns a string representing the specified object.
toUpperCase() Returns the calling string value converted to uppercase.
valueOf() Returns the primitive value of the specified object.

String HTML wrappers

Here is a list of each method which returns a copy of the string wrapped inside the appropriate HTML tag.

Method Description
anchor() Creates an HTML anchor that is used as a hypertext target.
big() Creates a string to be displayed in a big font as if it were in a <big> tag.
blink() Creates a string to blink as if it were in a <blink> tag.
bold() Creates a string to be displayed as bold as if it were in a <b> tag.
fixed() Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
fontcolor() Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
fontsize() Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
italics() Causes a string to be italic, as if it were in an <i> tag.
link() Creates an HTML hypertext link that requests another URL.
small() Causes a string to be displayed in a small font, as if it were in a <small> tag.
strike() Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
sub() Causes a string to be displayed as a subscript, as if it were in a <sub> tag
sup() Causes a string to be displayed as a superscript, as if it were in a <sup> tag

Array Methods

Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).
every() Returns true if every element in this array satisfies the provided testing function.
filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
map() Creates a new array with the results of calling a provided function on every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.
reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
some() Returns true if at least one element in this array satisfies the provided testing function.
toSource() Represents the source code of an object
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.

Date Methods:

Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date according to local time.
getDay() Returns the day of the week for the specified date according to local time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
getMilliseconds() Returns the milliseconds in the specified date according to local time.
getMinutes() Returns the minutes in the specified date according to local time.
getMonth() Returns the month in the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.
getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
getTimezoneOffset() Returns the time-zone offset in minutes for the current locale.
getUTCDate() Returns the day (date) of the month in the specified date according to universal time.
getUTCDay() Returns the day of the week in the specified date according to universal time.
getUTCFullYear() Returns the year in the specified date according to universal time.
getUTCHours() Returns the hours in the specified date according to universal time.
getUTCMilliseconds() Returns the milliseconds in the specified date according to universal time.
getUTCMinutes() Returns the minutes in the specified date according to universal time.
getUTCMonth() Returns the month in the specified date according to universal time.
getUTCSeconds() Returns the seconds in the specified date according to universal time.
getYear() Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.
setDate() Sets the day of the month for a specified date according to local time.
setFullYear() Sets the full year for a specified date according to local time.
setHours() Sets the hours for a specified date according to local time.
setMilliseconds() Sets the milliseconds for a specified date according to local time.
setMinutes() Sets the minutes for a specified date according to local time.
setMonth() Sets the month for a specified date according to local time.
setSeconds() Sets the seconds for a specified date according to local time.
setTime() Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
setUTCDate() Sets the day of the month for a specified date according to universal time.
setUTCFullYear() Sets the full year for a specified date according to universal time.
setUTCHours() Sets the hour for a specified date according to universal time.
setUTCMilliseconds() Sets the milliseconds for a specified date according to universal time.
setUTCMinutes() Sets the minutes for a specified date according to universal time.
setUTCMonth() Sets the month for a specified date according to universal time.
setUTCSeconds() Sets the seconds for a specified date according to universal time.
setYear() Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.
toDateString() Returns the "date" portion of the Date as a human-readable string.
toGMTString() Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.
toLocaleDateString() Returns the "date" portion of the Date as a string, using the current locale's conventions.
toLocaleFormat() Converts a date to a string, using a format string.
toLocaleString() Converts a date to a string, using the current locale's conventions.
toLocaleTimeString() Returns the "time" portion of the Date as a string, using the current locale's conventions.
toSource() Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.
toString() Returns a string representing the specified Date object.
toTimeString() Returns the "time" portion of the Date as a human-readable string.
toUTCString() Converts a date to a string, using the universal time convention.
valueOf() Returns the primitive value of a Date object.

Date Static Methods:

In addition to the many instance methods listed previously, the Date object also define two static methods. These methods are invoked through the Date( ) constructor.

Method Description
Date.parse( ) Parses a string representation of a date and time and returns the internal millisecond representation of that date.
Date.UTC( ) Returns the millisecond representation of the specified UTC date and time.

Math Methods

Method Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in radians) of a number.
atan2() Returns the arctangent of the quotient of its arguments.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number.
toSource() Returns the string "Math".

RegExp Methods:

Method Description
exec() Executes a search for a match in its string parameter.
test() Tests for a match in its string parameter.
toSource() Returns an object literal representing the specified object; you can use this value to create a new object.
toString() Returns a string representing the specified object.

 







Accessing the Objects Properties

You can effectively access an object's properties in one of two ways:

nameOfObject.nameOfProperty

or

nameOfObject["nameOfProperty"]

var person = {
    firstName: "James",
    lastName: "Patterson
};


The way you would access the person's firstName property from the code above would be:

person.firstName

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    var person = {
        firstName: "James",
        lastName : "Patterson",
        age       :  30
    };
    document.getElementById("tutorial").innerHTML =
    person.firstName + " " + person.lastName + " is " + person.age + " years old.";
    </script>

  </body>
</html>



The code above shows you how to access the firstName, lastName, and age properties using the nameOfObject.nameOfProperty method.


person["firstName"];

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    var person = {
        firstName: "James",
        lastName : "Patterson",
        age       :  30
    };
    document.getElementById("tutorial").innerHTML =
    person["firstName"] + " " + person["lastName"] + " is " + person["age"] + " years old.";
    </script>

  </body>
</html>



The code above shows you how to access the firstName, lastName, and age properties using the nameOfObject["nameOfProperty"] method.


Both Methods

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    var person = {
        firstName: "James",
        lastName : "Patterson",
        age       :  30
    };
    
    var a = person.age;
    
    document.getElementById("tutorial").innerHTML =
    person["firstName"] + " " + person.lastName + " is " + a + " years old.";
    </script>

  </body>
</html>



The code above shows you how to access the firstName, lastName, and age properties using both methods.

The output for all three examples: James Patterson is 30 years old.

Javascript properties are the most important part of any JS object. The properties are the values associated with the JS object. The values can be name, age, eye color, and really anything that would describe the object in further detail to a computer. The Javascript object is a collection of unordered properties or attributes that can be changed, added, deleted, and sometimes read only.

nameOfObject[expression] is another way to access a javascript property.

var x = "age";
person[x] or person.x would be how you access the value using this method.




Additional Properties to Add/Delete

You can add additional properties to any of your objects that are already created by giving it a value. The code below will show you how to add more properties to an object with only two fields:

var motorcycle = { year:2008, make:"Honda"};

To add an additional attribute to the object motorcycle:

motorcycle.model = "Shadow";

Let us add an additional attribute to the object for giggles

motorcycle.engineSize = 750;

We can delete a property from the list of attributes available for an object at will. The delete keyword will delete a property from an object's list of attributes.

delete motorcycle.engineSize;

The code above will delete the last entry we made to our object's attributes. The delete keyword will delete both the value of the property and the property itself. After being deleted, the property cannot be used unless it is added to the attributes list once again. The delete operator is designed specifically to be used on object properties, and yields no negative effects on variables or functions. The delete operator should not be used on predefined JS object properties, and doing so will probably crash your system, browser, or application.




For...in Loop

Javascript has a built in for.. in loop, which will loop through each property of an object one by one until the end of the object properties list. The block of code that lies in the for in loop will be executed once for each property found for the available object. Below is how to loop through the properties of an object:

for (variable in object) {
    Code;
}



<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
      var statement = "";
      var blank = " ";
      var person = {fname:"James", lname:"Patterson", age:30};
      var attr;

      for (attr in person) {
          statement += person[attr] + blank;
      }

      document.getElementById("tutorial").innerHTML = statement;
      
    </script>
  </body>
</html>



Output: James Patterson 30


<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
      var statement = "";
      var blank = " ";
      var vehicle= {year:2008, make:"Ford", model:"Mustang"};
      var attr;

      for (attr in vehicle) {
          statement += vehicle[attr] + blank;
      }

      document.getElementById("tutorial").innerHTML = statement;
      
    </script>
  </body>
</html>



Output: 2008 Ford Mustang

Both examples above show how to take an empty element with a specific id name, and add values to them. The values come from a Javascript object's attributes. First, you need to declare an empty string, since you plan on concatenating the information together. Next, you will need to create your object, person or vehicle, and create the object's attributes associated with each. The next declaration is just a place holder for looping through the attributes. The for in loop says that for every attribute in person/vehicle, concatenate the information found with the original empty string, and then force the result to be displayed inside the element with an id that equals tutorial.




Prototype Properties

Javascript objects will inherit the properties of their prototype. Every Javascript object has a prototype associated with it. The prototype is also an object. All Javascript objects will inherit the properties and methods from their associated prototype. Objects that are created using an object literal, also with the new Object() technique, will inherit from a prototype called Object.prototype. All objects inherit from the Object.prototype: Date, Array, RegExp, Function, and so on. The traditional way to create an object prototype is to use an object constructor function. The code below will show how to create an object constructor function and use it:

<!DOCTYPE html>
<html>
  <body>

    <p id="tutorial"></p>

    <script>
    
      function Vehicle(yr, mk, md) {
          this.year = yr;
          this.make = mk;
          this.model = md;
      }

      var myMotorcycle = new Vehicle(2008, "Honda", "Shadow");
      var myCar = new Vehicle(2004, "Ford", "Mustang");

      document.getElementById("tutorial").innerHTML =
      "My motorcyle is a " + myMotorcycle.year + " " +
      myMotorcycle.make + " " + myMotorcycle.model + ". My car is a " +
      myCar.year + " " + myCar.make + " " + myCar.model + ".";
    </script>

  </body>
</html>



Output: My motorcyle is a 2008 Honda Shadow. My car is a 2004 Ford Mustang.

With the use of a construction function, we are allowed to use the new keyword to create all new objects from the same prototype. The constructor function is the prototype for the vehicle objects. It is considered to be standard practice to name the constructor function with an upper case first letter; Vehicle, Person, Etc. Prototype properties must be hard coded within the javascript code, because the properties cannot be added to outside of the javascript code. The value of myCar.color is "undefined", because you cannot add a new property to a prototype the same way as you can add a new property to an existing object. To add a new property to a prototype, the only way is to add it to the constructor function yourself inside the of Javascript code. You cannot append additional properties dynamically, and then expect a result other than undefined.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>
        
        <p id="tutorial2"></p>

        <script>
        
            function Vehicle(yr, mk, md) {
                      this.year = yr;
                      this.make = mk;
                      this.model = md;
            }

            var myMotorcycle = new Vehicle(2008, "Honda", "Shadow");
              var myCar = new Vehicle(2004, "Ford", "Mustang");
            
            myCar.cylinders = 6;

            document.getElementById("tutorial").innerHTML =
            "My car's cylinder number: " + myCar.cylinders;
            
            Vehicle.color = "Green";
            
            document.getElementById("tutorial2").innerHTML =
            "My car's color: " + myCar.color;
            
        </script>
    </body>
</html>



Output: My car's cylinder number: 6

&

Output: My car's color: undefined.

Prototype properties can possess prototype values or default values. A constructor can also define methods within the function. The code below will show how to create a constructor function with a method as one of the properties. The constructor below creates a skeleton for a vehicle object; year, make, and model. The three attributes that all vehicles share. The this keyword is used again here to signal that we are using the currently accessed object. The method we define within the constructor will concatenate the information passed to the constructor via the parameters.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
        
         function Vehicle(yr, mk, md) {
             this.year = yr;
              this.make = mk;
              this.model = md;          
            this.information = function() {
                return this.year + " " + this.make + " " + this.model
            };
        }

        var myMotorcycle = new Vehicle(2008, "Honda", "Shadow");
        
        document.getElementById("tutorial").innerHTML =
        "Vehicle: " + myMotorcycle.information();
        
        </script>

    </body>
</html>



I do believe I mentioned you cannot add properties to a constructor after it has been coded, but you ultimately can. Using the prototype property, you can effectively add additional properties to any constructor after completion. The prototype property is also great for adding new methods to an existing prototype constructor. DO NOT modify standard Javascript objects because there could be unexpected results, and remember to only modify your own prototypes.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
        function Vehicle(yr, mk, md) {
          this.year = yr;
          this.make = mk;
          this.model = md;          
          this.information = function() {
            return this.year + " " + this.make + " " + this.model
          };
        }

        Vehicle.prototype.color = "Red";

        var myMotorbike = new Vehicle(2008, "Honda", "Shadow");

        document.getElementById("tutorial").innerHTML =
            "Vehicle: " + myMotorbike.information() + " is " + myMotorbike.color;
        </script>

    </body>
</html>




Next, we will take a look at Scope within Javascript

Just follow the buttons to continue the tutorial, Guest