Javascript object-oriented programming advanced features classic tutorial (worth adding to favorites) _ javascript skills

Source: Internet
Author: User
This article mainly introduces the advanced features of javascript object-oriented programming, and detailed the creation, access, deletion, object type, extension, and so on of javascript objects in the form of examples, for more information about the advanced features of javascript object-oriented programming, see the examples in this article. We will share this with you for your reference. The details are as follows:

1. Three ways to create an object:

First constructor: new Object

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

Method 2: Object Direct Volume

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

Third constructor: Definition type

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

2. Access Object

Access Object Attributes
Brackets: hero ['name']. ,
Point expression: hero. name.
If the accessed attribute does not exist, undefined is returned.
Method of accessing objects
Add a pair of brackets after the method name: hero. say ().
Like an access method for an access attribute: hero ['say'] ().

3. Delete attributes and Methods

// Create an empty object var hero ={}; // Add the property and method hero to the hero object. name = "JavaScript"; hero. value = "helloworld"; hero. sayName = function () {return "hello" + hero. name ;}; // test alert (hero. name); // output javascriptalert (hero. sayName (); // output hello javascript // delete the name attribute of the hero object delete hero. name; // test alert (hero. sayName (); // output hello undefined

4. Use this value

// Create an empty object var hero ={}; // Add the property and method hero to the hero object. name = "javascript"; hero. value = "helloworld"; hero. sayName = function () {return "hello" + this. name ;}; // test alert (hero. name); // output javascriptalert (hero. sayName (); // output hello javascript

Summary:

① Here this actually references "this object" or "Current object ".
② This is used by many users. Therefore, it is not recommended to use too much!

5. built-in objects

Built-in objects can be divided into three groups:

① Data encapsulation Class Object: including Object, Array, Boolean, Number, and String. These objects represent different data types in javascript and all have different typeof return values, undefined and null states.

② Tool-type objects, including Math, Date, and RegExp, are used to provide traversal objects.

③ Error objects-including general error objects and other special error objects. They can help us correct the working state of the program when some exceptions occur.

6. Object

Objects are the parent objects of all objects in javascript, which means that all objects inherit from Object objects.

Create an empty object:

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

7. Array object

Array objects are used to store multiple values in a single variable.

Create an empty Array object:

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

Example 1:

// String inversion example // define a String var str = "a, B, c, d, e, f, g"; // use the split () method of the String object, splits the string into an array var arr = str. split (","); // use the reverse () method of the Array object to reverse the order of elements in the Array. Arr = arr. reverse (); // test and print alert (arr. toString ());

8. String object

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

var str = "hello";var obj = new String("world");alert(typeof str); //typeof stringalert(typeof obj); //typeof object

Example 1:

// Determine whether the string contains the specified string example // define two strings to be judged var str = "abcdefg"; var substr = "efg "; /** define the function to determine whether a string contains the specified string ** first parameter: the string to be judged ** second parameter: the specified string */function sub (str, substr) {// define the String to be judged as the string object var String = new string (str); // intercept the String var result = string. substr (string. indexOf (substr), substr. length);/** determines whether the truncated string is null **, indicating that the string 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)

The function itself is also an object that contains methods and attributes. What we need to study now is another property of the function object-prototype.

Adding Methods and attributes using prototype
Use its own attributes to override prototype attributes
Extended built-in object
Adding Methods and attributes using prototype

Next, create a new function object and set some attributes 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 attributes and methods to the above Hero function object:

Hero.prototype.price = 100;Hero.prototype.rating = 3;Hero.prototype.getInfo = function(){ return "Rating: " + this.rating + " , Price: " + this.price;}alert(hero.getInfo()); //output Rating: 3 , Price: 100

The preceding method can also be used as follows:

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

Use its own attributes to override prototype attributes

What if the object's own attributes have the same name as the prototype attributes? The answer is that the object has a higher priority than the prototype.

function Hero(){ this.name = "jscript";}Hero.prototype.name = "javascript";var hero = new Hero();alert(hero.name); //output jscriptdelete hero.name;alert(hero.name); //output javascript

Extended built-in object

// Adds a judgment Function Array for the prototype Array object. prototype. inArray = function (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 (. inArray ("red"); // truealert (. inArray ("yellow"); // false

10. Inheritance

If both classes are of the same instance type, there is a certain relationship between them. We call the general relationship between the types of the same instance as "inheritance ".

The inheritance relationship must have at least three meanings:

① Sub-class instances can share the parent class methods.
② Subclass can overwrite the parent class method or extend the new method.
③ Both the subclass and the parent class are the "type" of the subclass instance ".

In javascript, "inheritance" is not supported ". That is to say, there is no inherited syntax in javascript. In this sense, javascript is not a direct object-oriented language.

11. prototype chain

Prototype chain is the default inheritance method defined in ECMAScript standards.

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 = 18;this.getAge = function(){return this.age};}B.prototype = new A();C.prototype = new B();

Explanation:

The object is directly created in the prototype attribute of object B, and the original prototype of these objects is not extended.

A new object is created through new A (), and then its prototype is overwritten.

Javascript is a language that relies entirely on objects, without the concept of class.

Therefore, you must use new A () to create an object, and then complete the inheritance work through the object attributes.

After such inheritance implementation is completed, any modification, rewriting, or deletion to A () will not affect B.

Only inherit from the prototype:

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 = 18;C.prototype.getAge = function(){return this.age};

Inheritance between objects (Extended content, but not) (Shortest copy)

// This function accepts an object and returns its copy function extendCopy (p) {var z ={}; // defines an empty Object z for (var I in p) {// var I = 0; I <p. length; I ++ z [I] = p [I]; // if both are processed as arrays, you can understand} // uber attribute: p is used as the parent level of z, point z to the prototype z. uber = p; return z;} // defines object a, but object a is not a function object var a = {name: "a", toStr: function () {return this. name ;}// defines object B, but object B is not a function object var B = extendCopy (a); B. name = "B"; B. toStr = function () {return this. uber. toStr () + "," + this. name ;}; // define Object c, but object c is not a function object var c = extendCopy (B); c. name = 18; alert (c. toStr (); // output a, B, 18

PS: Many of the Code formatting in the tutorial is not very standard. I recommend several javascript code formatting and beautification tools on this site for you to use:

JavaScript code formatting tool:

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

JavaScript code beautification/compression/formatting/encryption tools:

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

Jsmin online js compression tool:

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

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.