Home Web Front-end JS Tutorial In-depth understanding of objects in JavaScript_Basic knowledge

In-depth understanding of objects in JavaScript_Basic knowledge

May 16, 2016 pm 03:56 PM
javascript object

JavaScript is an object-oriented programming (OOP) language. A programming language can be called object-oriented and provides four basic capabilities to developers:

  • Encapsulation - stores relevant information, whether it is data or methods, or objects
  • Aggregation - Store one object inside another object
  • Inheritance - the ability of a class to depend on another class (or classes) for some of its properties and methods
  • Polymorphism - writing functions or methods that work in a variety of different ways

Objects are made up of properties. If a property contains a function, it is considered a method of an object, otherwise, the property is considered a property.
Object properties:

The properties of an object can be of any of the three basic data types, or any abstract data type, such as another object. Object properties are usually variables used internally by methods of the object, but can also be variables that are used globally and visible throughout the page.

The syntax for adding attributes is:

objectName.objectProperty = propertyValue;

Copy after login

Example:

The following is a simple example to illustrate how to use the "title" property of the file object to get the document title:

var str = document.title;

Copy after login


Object methods:

Methods tell an object to do something. There is little difference between a function and a method, except that a function statement is an independent unit and the method is attached to the object and can be referenced through this keyword.

Methods can be useful for everything from displaying an object's on-screen content to performing complex mathematical operations on a local set of properties and parameters.
Example:

Here is a simple example to illustrate how to use the write() method of the document object to write any content in the document:

document.write("This is test");

Copy after login


User-defined objects:

All user-defined objects and built-in objects are called descendants of objects.
new operator:

The new operator is used to create instances of objects. To create an object, the new operator is followed by the constructor method.

In the following example, the constructor methods Object(), Array(), and Date(). These constructors are built-in JavaScript functions.

var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");

Copy after login


Object() constructor:

Constructor is a function used to create and initialize objects. JavaScript provides a special constructor called Object() to construct objects. The return value of the Object() construct is assigned to a variable.

The variable contains a reference to the new object. Properties assigned to this object are invariants and are not defined using the var keyword.
Example 1:

This example demonstrates how to create an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();  // Create the object
  book.subject = "Perl"; // Assign properties to the object
  book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
  document.write("Book name is : " + book.subject + "<br>");
  document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

Copy after login


Example 2:

This example demonstrates how to create an object and a user-defined function. Here the this keyword is used to refer to the object that has been passed to the function:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
  this.title = title; 
  this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
  var myBook = new book("Perl", "Mohtashim");
  document.write("Book title is : " + myBook.title + "<br>");
  document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

Copy after login


Object defining method:

The previous example demonstrates how a constructor creates an object and assigns properties. However, we need to use the allocation method to complete the definition of an object.
Example:

Here is a simple example to illustrate how to add a function with an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
  this.price = amount; 
}

function book(title, author){
  this.title = title; 
  this.author = author;
  this.addPrice = addPrice; // Assign that method as property.
}

</script>
</head>
<body>
<script type="text/javascript">
  var myBook = new book("Perl", "Mohtashim");
  myBook.addPrice(100);
  document.write("Book title is : " + myBook.title + "<br>");
  document.write("Book author is : " + myBook.author + "<br>");
  document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

Copy after login


with keyword:

The with keyword is used as a shorthand to refer to the properties or methods of an object.

The object specified as a parameter becomes the default object for the duration of the following block. Properties and methods for objects can be found on unnamed objects.
Grammar

with (object){
  properties used without the object name and dot
}

Copy after login

Example:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
  with(this){
    price = amount; 
  }
}
function book(title, author){
  this.title = title; 
  this.author = author;
  this.price = 0;
  this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
  var myBook = new book("Perl", "Mohtashim");
  myBook.addPrice(100);
  document.write("Book title is : " + myBook.title + "<br>");
  document.write("Book author is : " + myBook.author + "<br>");
  document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Analyze the differences between heap and stack in Java and their application scenarios Analyze the differences between heap and stack in Java and their application scenarios Feb 24, 2024 pm 11:12 PM

The difference between Java heap and stack and application scenario analysis require specific code examples. In Java programs, heap and stack are two commonly used data structures, and they assume different roles and functions in memory. Understanding the difference between heap and stack is crucial to writing efficient Java programs. First, let's take a look at the Java heap. The heap is an area used to store objects. All objects created in the program are stored in the heap. The heap is where memory is dynamically allocated and released while the program is running. It is not subject to any restrictions and can be automatically allocated and released as needed.

See all articles