There are three major characteristics of object-oriented languages: inheritance, polymorphism, and encapsulation. Although Javascript does not provide natural syntax implementation for these three points, we can all achieve them through techniques such as prototype, so this statement does not seem to be excessive.
In Javascript, there are three ways to construct objects:
1. First of all, we need to clarify a concept. Javascript is a weakly typed language. On the one hand, it is reflected in the fact that Javascript variables and return types do not have strong types. Constrained, on the other hand, Javascript can add arbitrary properties and methods to objects. Based on this, we can write code like this:
< ;script type="text/javascript">
var person = {};
person.name = "Fei Linsha";
person.age = 21;
person.Introduce = function () {
alert("My name is " this.name ".I'm " this.age);
};
person.Introduce();
The person here is an object we constructed.
2. We can also use JSON to construct an object.
Is this very similar to what we proposed in C# 3.0 What about anonymous objects?
protected void Page_Load(object sender, EventArgs e)
{
var person = new
{
name = "Fei Linsha",
age = 21
};
Response.Write("My name is " person.name ".I'm " person.age);
}
The difference is that in Javascript, a function is a type, so it can be assigned to a variable, but C# cannot.
But we see in the above two methods that we define an object separately. Next let's abstract them into a class.
But here, we see that the attributes have been hard-coded, and we have no way to customize each object individually. The solution is simple:
Okay, let’s compare the second and third writing methods. They are equivalent. In the second way of writing, a JSON object is actually constructed, and we know that JSON is essentially a key-value pair, so can we understand an object in the same way?
Let’s try writing a test code like this:
There is no problem with this code. First, use traversal to find all the keys (attributes and method names) of the person. Then we use indexing to access the name attribute of the person object.
There is no problem with these, but have we seen an extended problem? From the perspective of traditional object-oriented languages, name and age should belong to private variables, so is this simple access using person destroyed? What about encapsulation?
Remember what we said in the previous article? Those with var are called variables, and those without var are called attributes. So if we change the code to look like this.
This can be encapsulated very well. This is also the way of encapsulation in Javascript.
Okay, that’s it for Javascript classes and objects, but there are still some problems here. We’ll mention that below.