JavaScript object

JavaScript is an object-oriented programming language (OOP), but it is different from ordinary object-oriented languages ​​such as C++ and Java. For example, there is no concept of class in JavaScript. Therefore, when writing JavaScript code according to OOP thinking, it always feels a little unnatural.

In fact, JavaScript is an object-based language. It can be considered that almost everything in JavaScript is an object. In the previous tutorials and examples, although we barely mentioned the concept of objects, after studying this chapter, you will know that they are actually based on objects.

What is an object?

Object is a collection of properties and methods. Let's use a simple example to help understand what an object is and some concepts related to objects. For example, a person is an object, then:

Properties and methods: A person has a name, height, weight and other characteristics. These characteristics are called the attributes of the object. People can talk and walk. We call this ability the method of an object.

Private methods and public methods: A person can write programs after learning a programming language, and can be a translator after learning a foreign language. This ability that only individual objects have is called the private method of the object. On the contrary, the methods above that everyone has, such as talking and walking, are called public methods of the object.

Encapsulation: The same two people who have learned a programming language can write programs, but because they are two different objects, there are often differences in how to write programs. Some data and code of an object can be private and cannot be accessed by the outside world, which is called encapsulation.

Inheritance: Inheritance is a concept in classes. Inheritance means that a subclass obtains the properties and methods of the parent class (except private properties and methods) by inheriting (extends) from the parent class. This is like a big tree, layer by layer through inheritance, making the final program clear and powerful. Since the JavaScript language does not have the concept of classes, it does not directly provide inheritance capabilities. However, many people and some JavaScript frameworks are now trying to give JavaScript the ability to inherit.

Polymorphism: Polymorphism refers to the ability of different things to have different manifestations. The polymorphism mechanism allows objects with different internal structures to share the same external interface, reducing code complexity in this way. Unfortunately, like inheritance, JavaScript does not support polymorphism, a very important concept in OOP. Of course, there are also many people and JavaScript frameworks trying to indirectly implement polymorphism in JavaScript.

In view of the length and the purpose of this tutorial, some basic concepts about objects are briefly described here. Object-oriented programming is a specialized subject. Interested students can read other specialized works on OOP.

Accessing the properties of an object

Properties are values ​​associated with the object.

The syntax for accessing object properties is:

objectName.propertyName

This example uses the length property of the String object. 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

Methods for accessing objects

Methods are actions that can be performed on an object.

You can call methods through the following syntax:

objectName.methodName()

This example uses the toUpperCase() method of the String object. Convert the 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!

Use functions to construct objects:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
function person(firstname,age){
this.firstname=firstname;
this.age=age;
}
myFather=new person("John",50);
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>

Create JavaScript object instances

Once you have the object constructor, you can create a new object instance like this:

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

Add properties to JavaScript objects

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

Assuming personObj 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


Create a custom JavaScript object

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script>
  // 定义构造函数,并设定一个属性
    function Person(name)
    {
    this.name = name;
    }
    // 为 Person 增加一个方法
    Person.prototype.showName = function()
    {
    alert("我叫" + this.name);
    };
    // new 关键字实例化一个对象
    var Tom = new Person("Tom");
    // 运行该对象内的 showName() 方法
    Tom.showName();
</script>
</head>
<body>
</body>
</html>

As shown in the above example, we set the object name attribute in the constructor and pass the object's prototype Add a showName() method to the attribute, and finally instantiate an object through the new keyword.

JavaScript Classes

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

In JavaScript, classes are not created, nor are objects created from 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)
{
Executed code...
}

## Note: The code block in the for...in loop will be executed once for each attribute.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
     var x;
     var txt="";
     var person={fname:"Bill",age:56}; 
     for (x in person){
        txt=txt + person[x];
     }
     document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script> var x var mycars = new Array() mycars[0] = "Saab" mycars[1] = "Volvo" mycars[2] = "BMW" for (x in mycars) { document.write(mycars[x] + "<br />") } </script> </head> <body> </body> </html>
submitReset Code