Programming | objects
Javasciprt is a good choice for writing object-oriented Web applications. It can support OOP. Because it supports inheritance through prototypes as well as through properties and methods. Many developers try to discard JS, trying to use C # Or Java is just because JS is not the object-oriented language he thinks fit. Many people do not realize that JavaScript supports inheritance. When you write object-oriented code. It can give you very powerful energy. You can also use it to write reusable, encapsulated code.
Why is the object so great?
The success of object-oriented thinking is because it imitates the connection of things and things in reality. Things have attributes and methods. If we describe a lamp, we would say its height and width, such as 12CM. " Turn on the light "This action is the way it is. When it is in an open state. It can be lit a little or a little darker (that is, the brightness of this property value becomes larger or smaller).
JavaScript gives the ability to create objects for Web applications. Objects are triggered when they are needed, and can be instantiated many times after the code is encapsulated.
To create an object with the new object ()
There are several ways to create objects in JavaScript, and different methods can be used on different occasions. The simplest is to use the new operator, for example:
<script language= "javascript" type= "Text/javascript" >
<!--
person = new Object ()
Person.name = "Tim Scarfe"
Person.height = "6Ft"
Person.run = function () {
This.state = "Running"
This.speed = "4ms^-1"
}
-->
</script>
We defined the object of person in this example, and then added its properties and methods. In this example, there are two attributes in the custom method.
Create an object with a literal notation literal notation
You can also create objects with text notation, but JavaScript is more than 1.2 versions. It is created in a variety of ways.
<script language= "javascript" type= "Text/javascript" >
<!--
Object literals
Timobject = {
Property1: "Hello",
Property2: "Mmmmmm",
Property3: ["MMM", 2, 3, 6, "KKK"],
Method1:function () {alert ("method had been called" + this.property1)}
};
Timobject.method1 ();
Alert (TIMOBJECT.PROPERTY3)//would yield 3
var circle = {x:0, y:0, radius:2}//Another example
Nesting is no problem.
var rectangle = {
Upperleft: {x:2, y:2},
Lowerright: {x:4, y:4}
}
Alert (rectangle.upperleft.x)//would yield 2
-->
</script>
A literal notation is an array, or it can be any JavaScript expression or value.
Creating a custom object with the new operator or text mark is simple, is also logical. But its biggest drawback is that the results are not reusable. It's not easy to initialize the creation object with a different version. For example, the first example above, if the name of person is not "Tim Scarfe", That way we have to redefine the whole object just to fit in with its little change.