Working With Objects - MDN
MDN article called Working With Objects
by Nirvanachain
HTML
<!-- URL:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects
-->
JavaScript
function Car(make, model, year) {
// Notice the use of this to assign values to the object's
// properties based on the values passed to the function.
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Eagle", "Talon TSi", 1993);
// This statement creates mycar and assigns it the specified values
// for its properties. Then the value of mycar.make is the string
// "Eagle", mycar.year is the integer 1993, and so on.
// An object can have a property that is itself another object. For
// example, suppose you define an object called person as follows:
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// and then instantiate two new person objects as follows:
var rand = new Person("Rand McKinnon", 33, "M");
var ken = new Person("Ken Jones", 39, "M");
// Then, you can rewrite the definition of car to include an owner
// property that takes a person object, as follows:
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
// To instantiate the new objects, you then use the following:
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
var car2 = new Car("Nissan", "300ZX", 1992, ken);
// Notice that instead of passing a literal string or integer value
// when creating the new objects, the above statements pass the objects
// rand and ken as the arguments for the owners. Then if you want to find
// out the name of the owner of car2, you can access the following property:
console.log(car2.owner.name);