JavaScript Object-oriented programming advanced features classic tutorials (worth collecting) _javascript tips

Source: Internet
Author: User
Tags extend inheritance shallow copy

This article illustrates the advanced features of JavaScript object-oriented programming. Share to everyone for your reference, specific as follows:

1. Three ways to create objects:

The first method of construction: New Object

var a = new Object ();
a.x = 1, a.y = 2;

The second method of construction: Object Direct Quantity

var B = {x:1, y:2};

The third method of construction: Defining types

function point (x, y) {
 this.x = x;
 This.y = y;
}
var p = new Point (1,2);

2. Access to Objects

Accessing the properties of an object
Bracket notation: hero[' name '. 、
Dot notation: Hero.name.
If the accessed property does not exist, it returns undefined.
Ways to Access Objects
Add a pair of parentheses after the method name: Hero.say ().
Like Access property An access method: hero[' say '] ().

3. Delete Properties and methods

Create an empty object
var hero = {};
Add properties and methods to the Hero object
hero.name = "JavaScript";
Hero.value = "HelloWorld";
Hero.sayname = function () {return "Hello" + hero.name;};
Test
alert (hero.name);//output javascript
alert (Hero.sayname ());//output Hello JavaScript
// Deletes the Hero object's Name property delete
hero.name;
Test
alert (Hero.sayname ());//output Hello undefined

4. Use this value

Create an empty object
var hero = {};
Add properties and methods to the Hero object
Hero.name = "JavaScript";
Hero.value = "HelloWorld";
Hero.sayname = function () {return "Hello" + this.name;};
Test
alert (hero.name);//output javascript
alert (Hero.sayname ());//output Hello JavaScript

Summarize:

① here is actually referring to "this object" or "current object".
②this usage, most people use more problems. So do not recommend too much use!

5. Built-in objects

The built-in objects can be roughly grouped into three groups:

① data encapsulates class objects--including object, Array, Boolean, number, and string. These objects represent different data types in JavaScript, and they all have different typeof return values, as well as undefined and null states.

The ② tool class object--including math, Date, RegExp, and so on--to provide traversal objects.

③ error class objects-including generic error objects and various other, more specific, error class objects. They can help us correct the working state of the program when certain anomalies occur.

6.Object objects

object is the parent object of all objects in JavaScript, which means that all objects inherit from Object objects.

To create an empty object:

var object = {};
var obj = new Object ();

7.Array objects

The array object is used to store multiple values in a single variable.

Create an empty array object:

var object = {};
var obj = new Array ();

For example 1:

Reverse string Example
//define a string
var str = "A,b,c,d,e,f,g";
Use the split () method of the string object to cut the string into an array of
var arr = str.split (",");
Use the reverse () method of the array object to reverse the order of the elements in the array.
arr = Arr.reverse ();
Test Print
alert (arr.tostring ());

8.String objects

The difference between a string object and a basic string type:

var str = "Hello";
var obj = new String ("World");
Alert (typeof str); typeof string
alert (typeof obj);//typeof Object

For example 1:

Determines whether a string contains the specified string sample
//Definition two string to be judged
var str = "ABCDEFG";
var substr = "EFG";
*
* Defines a function that determines whether a string contains a specified string * The  first parameter: The string to be judged *  * Second parameter: The specified string
/function sub (str, SUBSTR) {
////defines the string of the judgment as a Strings object
var string = new string (str);
Intercept the judgment string
var result = String.substr (String.IndexOf (substr), substr.length);
* * To determine if the intercepted string is empty
* *  is NULL, the description does not contain the specified string
* * is  NOT NULL, description contains the specified string
/if (RESULT==SUBSTR) { return
true;
} else{return
false;
}
Alert (sub (STR,SUBSTR));

9. Prototype (prototype)

The function itself is also an object that contains methods and properties. And now we're going to look at another property--prototype of the function object.

Adding methods and attributes using prototypes
Overriding prototype properties with its own properties
Extend built-in objects
Adding methods and attributes using prototypes

The following creates a new function object and sets some properties and methods:

function Hero (name, color) {
 this.name = name;
 This.color = color;
 This.whatareyou = function () {return
 "I am a" + This.color + "" + THIS.name;
 }
}
var hero = new Hero ("JavaScript", "Red");
Alert (hero.whatareyou ()); Output I am a red javascript

Add some properties and methods for the Hero function object above:

Hero.prototype.price = m;
Hero.prototype.rating = 3;
Hero.prototype.getInfo = function () {return
 "Rating: + this.rating +", Price: "+ This.price;
}
Alert (Hero.getinfo ()); Output Rating:3, price:100

The above way, you can do this:

Hero.prototype = {
 price:100,
 rating:3,
 getinfo:function () {return
   "rating:" + this.rating + " , Price: "+ This.price;
 }
};

Overriding prototype properties with its own properties

What if the object's own property has the same name as the prototype property? The answer is that the object's own properties have precedence over the prototype property.

function Hero () {
 this.name = "JScript";
}
Hero.prototype.name = "JavaScript";
var hero = new Hero ();
alert (hero.name); Output JScript
delete hero.name;
alert (hero.name); Output JavaScript

Extend built-in objects

Adds a function for the prototype Array object
Array.prototype.inArray = functions (color) {for
 (var i = 0, len = this.length; i < Len; i++) {
 if (this[i] = = color) {return
 true;
 }
 }
 return false;
}
Define an Array object
var a = ["Red", "green", "Blue"];
Test
alert (A.inarray ("Red"));//true
alert (A.inarray ("yellow"));//false

10. Inheritance

If all two classes are of the same instance, there is some relationship between them, and we call the generalization relationship between the types of the same instance "inheritance".

An inheritance relationship contains at least three levels of meaning:

Instances of ① subclasses can share methods of the parent class.
② subclasses can override methods of the parent class or extend new methods.
The ③ subclass and the parent class are all "types" of subclass instances.

in JavaScript, inheritance is not supported. In other words, there is no inherited syntax in JavaScript. In this sense, JavaScript is not a direct object-oriented language .

11. Prototype Chain

The prototype chain is the default inheritance method of the ECMAScript standard setting.

For example:

function A () {
this.name = "a";
this.tostring = function () {return this.name};
}
Function B () {
this.name = "B";
}
Function C () {
this.name = "C";
This.age =;
This.getage = function () {return this.age};
}
B.prototype = new A ();
C.prototype = new B ();

EXPLANATION Note:

Creating objects directly in the prototype property of a B object does not extend the original prototype of those objects.

A new entity is created by using new A (), and it is used to overwrite the object's prototype.

JavaScript is a language that relies entirely on objects, and there is no concept of classes (class).

Therefore, you need to create an entity directly with new A () before you can complete the related inheritance work through the entity's properties.

After such an inheritance implementation is completed, any modifications, overrides, or deletions made to a () do not have an effect on B ().

Inherit from prototype only:

function A () {}
a.prototype.name = "a";
a.prototype.tostring = function () {return this.name};
function B () {}
b.prototype = A.prototype;
B.prototype.name = "B";
function C () {}
c.prototype = B.prototype;
C.prototype.name = "C";
C.prototype.age =;
C.prototype.getage = function () {return this.age};

Inheritance between objects (extended content, can not be) (shallow copy)

The function accepts an object and returns its replica
function extendcopy (p) {
 var z = {};//define an empty object Z for
 (var i in P) {//var i =0 i < P.L Ength; i++
 Z[i] = p[i];//All as an array, you can understand
 the
 //uber property: P As the parent of Z, and Z to the prototype
 z.uber = p;
 return z;
}
Object A is defined, but object A is not a function object 
var a = {
 name: "A",
 tostr:function () {return this.name}
}
Object B is defined, but object B is not 
a function object var b = Extendcopy (a);
B.name = "B";
B.tostr = function () {return this.uber.toStr () + "," + this.name;};
Object c is defined, but object C is not a function object 
var c = extendcopy (b);
C.name =;
Alert (C.tostr ()); Output A, B, 18

PS: Many of the tutorials in the code layout is not very standard, small series here recommend a number of this site JavaScript code format Landscaping Tools for everyone to use:

JavaScript Code formatting tool:

Http://tools.jb51.net/code/js

JavaScript code Landscaping/compression/formatting/encryption Tools:

Http://tools.jb51.net/code/jscompress

Jsmin Online JS compression tool:

Http://tools.jb51.net/code/jsmincompress

For more on JavaScript related content to view the site topics: "JavaScript object-oriented Tutorial", "javascript json operation tips Summary", "JavaScript switching effects and techniques summary", " JavaScript Search Algorithm Skills Summary, "JavaScript animation effects and techniques Summary", "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and skills summary" and The summary of JavaScript mathematical operational usage

I hope this article will help you with JavaScript programming.

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.