May 06, 2021 JavaScript
4. Access the properties of the object
5. The method of accessing the object
8.. Use the object constructor
10.. Create a JavaScript object instance
11.. Add properties to the JavaScript object
12.. Add methods to JavaScript objects
Everything in JavaScript is an object: strings, values, arrays, functions...
In addition, JavaScript allows custom objects.
JavaScript provides several built-in objects, such as String, Date, Array, and so on. Objects are just special data types with properties and methods.
An object is just a special kind of data. The object owns the property and the method.
The property is the value associated with the object.
The syntax for accessing object properties is:
This example uses the length property of the String object to get the length of the string:
After the above code is executed, the value of x will be:
Methods are actions that can be performed on an object.
You can call a method using the following syntax:
This example uses the toUpperCase() method of the String object to convert text to capital:
After the above code is executed, the value of x will be:
JavaScript enables you to define and create your own objects.
There are two different ways to create a new object:
This example creates a new instance of an object and adds four properties to it:
Alternative syntax (using object literals):
Tips:You can practice using javaScript programming in this site
JavaScript object action!This example uses a function to construct an object:
In JavaScript, this usually points to the function itself that we are executing, or to the object to which the function belongs (runtime)
Once you have an object constructor, you can create a new object instance, like this:
You can add new properties to an existing object by assigning a value to it:
Suppose personObj already exists - you can add these new properties to it: firstname, lastname, age, and eyecolor:
After the above code is executed, the value of x will be:
A method is nothing more than a function attached to an object.
Methods for defining objects within constructor functions:
The value of the changeName() function name is assigned to the lastname property of the person.
JavaScript is an object-oriented language, but JavaScript does not use classes.
In JavaScript, no classes are created, nor are objects created through classes (as in other object-oriented languages).
JavaScript is prototype-based, not class-based.
JavaScript for... The in statement loops through the properties of the object.
Note: for... The block of code in the in loop is executed once for each property.
Loop through the properties of the object:
Please study it carefully and examine its use:
Try it out
Easy to learn JavaScript: An overview of JavaScript objects