JavaScript Object oriented primary object-oriented programming basics

Source: Internet
Author: User
Tags eval inheritance
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:
Copy Code code 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>


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.
Copy Code code 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])//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.

Construction and prototyping of objects

In the world of OOP, defining objects with previous methods is limited on many occasions. We need a way to create objects that can be used multiple times without redefining them. Objects can be assigned different values each time they are instantiated. The standard way to achieve this is to use an object constructor function.

An object builder is nothing more than a regular JavaScript function, like a container (defining parameters, calling other functions, and so on). The difference between them is that constructor functions are called by the new operator. (as you'll see in the example below). Object definitions based on the form of functional syntax, we can make it work best.


Let's use the real world cat to give an example. The cat's name and color are the properties of the cat. Meeyow (cat bark) is one of its methods. It is important that any different cat may have different name and Meeyow calls. To build an object class that adapts to these features, we'll use the Object Builder .
Copy Code code 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 builder, its properties and methods are defined in the body of the function with this, and the object defined by the object constructor is instantiated with new. How can we be very easy to define multiple instances of cat. Each has its own name, which is the flexibility that the object builder brings to us. .
The constructor establishes the blueprint for the object. Not the object itself.
Add a method to the prototype.
In the example we see above, the object's method is defined in the constructor. Another way to achieve this is through the prototype (prototype). XXX
A prototype is a form of JavaScript inheritance. We can create a method after defining the object. All instances of the original object will be shared.
Let's extend the original Cat object. Add a method of renaming. In a prototype way.
Copy Code code 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 used the keyword prototype to implement the ChangeName method immediately after the object definition. This method is shared by all instances.
Overloading JavaScript objects with prototypes (prototype)
Prototypes work on custom objects and on selective overloaded objects. such as Date () or String this can be open-ended.
Subclasses and Super Classes
In Java and C + +, there are external concepts about class hierarchies. 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 is extended, or sub-classed so the resulting subclass can inherit its parent ' s behavior. As we have seen, JavaScript supports prototype inheritance of class instead. It ' s possible for inheritance to happen other ways, however.

The following is an example of inheritance through functions.

The following example shows how to inherit through a function.
Copy Code code as follows:
<script language= "javascript" type= "Text/javascript" >
<!--

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>

The prototype based on inheritance is remote. For JavaScript applications on many occasions.
(prototype based inheritance is useful in many JavaScript applications.)

Object as a federated array
As you know, (.) Operators can be used to store. The [] operator is used to manipulate the array.
<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 does I loop through properties in an object?
You are need to use a for/in loop.
We can iterate through the object's properties through a for in loop.

<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 this in the object syntax the property is a identifier, whereas in the array syntax, it ' S a string. The obvious benefits of using an array syntax to access a object is because of the literal data type, you can easily conc At strings and play around with them to access an object. For this to work with the standard syntax, a eval () would need to be used.
It should be noted that the object's properties are only an identifier character, although in an array is a string, because it is a literal data type, so it is advantageous to use an array of ways to manipulate an object. You can also easily access an object in a standard statement. The eval () function may be used at this time.
<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>
The things on the internet are wrong too much, jb51.net the revised test
<script> function Car (color,door) {this.color = color; This.doors = door; This.arr = new Array ("AA", "BB"); } car.prototype.showcolor=function () {alert (this.color); var car1 = new Car ("Red", 4); var car2 = new Car ("Blue", 4); Car1.arr.push ("CC"); Car1.arr.unshift ("DD"); Alert (car1.arr.toString ()); Car1.showcolor (); OUTPUT:AA,BB,CC Car2.showcolor (); OUTPUT:AA,BB </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
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.