Javascript object oriented Object-Oriented Programming

Source: Internet
Author: User

Use new Object () to create an Object
There are several methods for creating objects in javascript. Different methods can be used in different scenarios. The simplest is to use the new operator, for example: Copy codeThe Code is as follows: <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>

In this example, the person object is defined and its attributes and methods are added. In this example, the custom method has two attributes.

Use Literal Notation to create an object
You can also use text marks to create objects, but javascript 1.2 or a later version is required. It can be created in a variety of forms.Copy codeThe Code is as follows: <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 [2]) // will 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) // will yield 2

// -->
</Script>

The text mark is an array or any javascript expression or value.

Creating a custom object with the new operator or text mark is simple and logical. but its biggest drawback is that the results cannot be reused. it is not easy to use different versions to initialize object creation. for example, in the first example above, if the name of person is not "Tim Scarfe", we have to redefine the entire object to adapt to a slight change in it.

Object Construction and prototype

In the OOP world, defining objects using previous methods has limits in many cases. we need a method to create an object. The type can be used multiple times without being redefined. objects can be assigned different values on demand each time they are instantiated. the standard method to achieve this goal is to use the object constructor function.

An object constructor is just a javascript function with rules. It is like a container (defining parameters, calling other functions, etc ). the difference between the two is that the constructor function is called by the new operator. (you will see in the following example ). based on the object definition in the form of function syntax, we can make it work best.

Let's use cats in the real world as an example. the cat name and color are attributes of the cat. meeyow is one of its methods. it is important that any cat may have different names and meeyow voices. to create an object class to adapt to these features, we will use the object constructor.Copy codeThe Code is as follows: <script language = "javascript" type = "text/javascript">
<! --

Function cat (name ){
This. name = name;
This. talk = function (){
Alert (this. name + "say meeow! ")
}
}

Cat1 = new cat ("felix ")
Cat1.talk () // alerts "felix says meeow! "

Cat2 = new cat ("ginger ")
Cat2.talk () // alerts "ginger says meeow! "

// -->
</Script>

Here, the function cat () is an object constructor. Its Attributes and methods are defined by this in the function body, and the objects defined by the object constructor are instantiated by new. how can we easily define multiple cat instances. every one has its own name, which is the flexibility that the object constructor brings to us.
The constructor creates a blueprint for the object, not the object itself.
Add a method to the prototype.
In the example we see above, the object method is defined in the constructor. Another way of implementation is through prototype. xxx
Prototype is a form of javascript inheritance. We can create a method after defining the object. All objects will be shared.
Let's extend the original cat object. Add a renamed method. Use prototype.Copy codeThe Code is as follows: <script language = "javascript" type = "text/javascript">
<! --

Cat. prototype. changeName = function (name ){
This. name = name;
}

FirstCat = new cat ("pursur ")
FirstCat. changeName ("Bill ")
FirstCat. talk () // alerts "Bill says meeow! "

// -->
</Script>

As you can see, we only use the prototype keyword to implement the changeName method immediately after the object definition. This method is shared by all instances.
Reload javascript objects with prototype
The prototype can work on custom objects and selective overloaded objects. For example, Date () or String may be endless.
Subclass and superclass
In JAVA and C ++, there is an external concept of class hierarchy. Each class can have a role.
In Java and C ++, there is an explicit concept of the class hierarchy. i. e. every class can have a super class from which it inherits properties and methods. any class can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. as we have seen, javascript supports prototype inheritance instead of class based. it's possible for inheritance to happen other ways, however.

The following is an example of inheritance through funwing.

The following example demonstrates how to inherit functions.Copy codeThe Code is as follows: <script language = "javascript" type = "text/javascript">
<! --

// Thanks to webreference

Function superClass (){
This. supertest = superTest; // attach method superTest
}

Function subClass (){
This. inheritFrom = superClass;
This. inheritFrom ();
This. subtest = subTest; // attach method subTest
}

Function superTest (){
Return "superTest ";
}

Function subTest (){
Return "subTest ";
}

Var newClass = new subClass ();

Alert (newClass. subtest (); // yields "subTest"
Alert (newClass. supertest (); // yields "superTest"

// -->
</Script>

Inheritance-based prototype is far away for javascript applications in many scenarios.
(Prototype-based inheritance is very useful in many javascript applications .)

Object as a Union Array
As you know, the (.) operator can be used to store. [] operators used to operate arrays.
<Script language = "javascript" type = "text/javascript">
<! --

// These are the same
Object. property
Object ["property"]

// -->
</Script>

<Script language = "javascript">
<! --
Function Circle (xPoint, yPoint, radius ){
This. x = xPoint;
This. y = yPoint;
This. r = radius;
}

Var aCircle = new Circle (5, 11, 99 );
Alert (aCircle. x );
Alert (aCircle ["x"]);
// -->
</SCRIPT>
How do I loop through properties in an object?
You need to use a for/in loop.
We can use the for in loop to traverse object attributes.

<Script language = "javascript" type = "text/javascript">
<! --

Var testObj = {
Prop1: "hello ",
Prop2: "hello2 ",
Prop3: new Array ("hello", 1, 2)
}
For (x in testObj) alert (x + "-" + testObj [x])
// -->
</Script>
<Script language = "javascript">
<! --
Var Circle = {x: 0, y: 1, radius: 2} // another example

For (p in Circle)
Alert (p + "-" + Circle [p])
// -->
</SCRIPT>

The important thing to notice is that in the object syntax the property is an identifier, whereas in the array syntax, it's a string. the obvious benefits of using an array syntax to access an object is because of the literal data type, you can easily concat strings and play around with them to access an object. for this to work with the standard syntax, an eval () wocould need to be used.
It should be noted that the object property is only an identifier character, although it is a string in an array, because it is a literal data type, therefore, it is helpful to operate an object using arrays. You can also easily access an object in a standard statement. In this case, the eval () function may be used.
<Script language = "javascript" type = "text/javascript">
<! --

TestObj = {
Prop1: "hello ",
Prop2: "hello2 ",
Prop3: new Array ("helloa", 1, 2)
}

For (x in testObj) alert (x + "-" + testObj [x])
Var prop3 = testObj ["prop3"];
Alert (prop3 );
// Alert (prop [1]);
Alert (typeof (prop3 ));
Alert (eval (prop3) [1]);
Alert (typeof (eval (prop3) [1]);

// -->
</Script>
There are too many online errors. In the test after jb51.net is corrected

[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.