JavaScript Object


Everything in JavaScript is an object: strings, numbers, arrays, functions...

Furthermore, JavaScript allows custom objects.


Everything is an object

JavaScript provides multiple built-in objects, such as String, Date, Array, etc. Objects are special data types that have properties and methods.

  • A boolean can be an object.
  • A number can be an object.
  • A string can also be an object
  • A date is an object
  • Math and regular expressions are also objects
  • An array is an object
  • Even functions can be objects

JavaScript Objects

An object is just a special type of data. Objects havepropertiesandmethods。


Accessing Object Properties

Properties are values associated with an object.

The syntax for accessing an object property is:

objectName.propertyName

This example uses the length property of the String object to get the length of the string:

var message="Hello World!";
var x=message.length;

After the above code is executed, the value of x will be:

12


Accessing Object Methods

Methods are actions that can be performed on objects.

You can call a method using the following syntax:

objectName.methodName()

This example uses the toUpperCase() method of the String object to convert text to uppercase:

var message="Hello world!";
var x=message.toUpperCase();

After the above code is executed, the value of x will be:

HELLO WORLD!


Creating JavaScript Objects

With JavaScript, you can define and create your own objects.

There are two different ways to create new objects:

  • Use Object to define and create an instance of an object.
  • Use a function to define an object, then create new object instances.

Using Object

In JavaScript, almost all objects are instances of the Object type; they all inherit properties and methods from Object.prototype.

The Object constructor creates an object wrapper.

The Object constructor creates an object based on the given argument, specifically as follows:

  • If the given value is null or undefined, an empty object will be created and returned.
  • If a primitive value is passed in, an object of its wrapper type will be constructed.
  • If a reference-type value is passed in, that value will still be returned; variables copied from it retain the same reference address as the source object.
  • When called in a non-constructor form, Object behaves the same as new Object().

Syntax format:

// 以构造函数形式来调用
new Object([value])

value can be any value.

The following example uses Object to generate a boolean object:

// 等价于 o = new Boolean(true);
var o = new Object(true);

This example creates a new instance of an object and adds four properties to it:

Example

person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";

Try it yourself »

You can also use an object literal to create an object, with the following syntax:

var myObject = {
    key1: value1,
    key2: value2,
    // 更多键值对...
};
  • myObject:Variable name, used to reference the entire object.
  • key1, key2:Property name, can be a string or an identifier.
  • value1, value2:The property value can be any JavaScript data type, including numbers, strings, booleans, functions, arrays, or even other objects.

Example

var person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    isStudent: false,
    greet: function() {
        console.log('Hello, I am ' + this.firstName + ' ' + this.lastName);
    }
};

console.log(person.firstName);  // Output: John
person.greet();  // Output: Hello, I am John Doe

Example

person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

Try it yourself »

A JavaScript object is aname:valuecollection.



Using Object Constructors

This example uses a function to construct an object:

Example

function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }

Try it yourself »

In JavaScript, this usually refers to the function itself that we are executing, or to the object to which the function belongs (at runtime).


Creating JavaScript Object Instances

Once you have an object constructor, you can create new object instances, like this:

var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");


Adding Properties to JavaScript Objects

You can add new properties to an existing object by assigning values to the object:

Assuming the person object already exists - you can add these new properties to it: firstname, lastname, age, and eyecolor:

person.firstname="John";
person.lastname="Doe";
person.age=30;
person.eyecolor="blue";

x=person.firstname;

After the above code is executed, the value of x will be:

John


Adding Methods to JavaScript Objects

Methods are simply functions attached to objects.

Define the object's method inside the constructor function:

function person(firstname,lastname,age,eyecolor)
{
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;

    this.changeName=changeName;
    function changeName(name)
    {
        this.lastname=name;
    }
}

The changeName() function assigns the value of name to person's lastname property.

Now you can try it:

myMother.changeName("Doe");

Try it yourself »

JavaScript Classes

JavaScript is an object-oriented language, but JavaScript does not use classes.

In JavaScript, you do not create classes, nor do you create objects through classes (as in other object-oriented languages).

JavaScript is prototype-based, not class-based.


JavaScript for...in Loop

The JavaScript for...in statement loops through the properties of an object.

Syntax

for (variable in object)
{
    执行的代码……
}

Note:The code block inside the for...in loop will be executed once for each property.

Example

Loop through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; }

Try it yourself »


JavaScript Objects are Mutable

Objects are mutable; they are passed by reference.

The person object in the following example does not create a copy:

var x = person;  // 不会创建 person 的副本,是引用

If you modify x, the properties of person will also change:

Example

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"} var x = person; x.age = 10; //Both x.age and person.age will change

Try it yourself »
Other Extensions