This article describes the advanced features of object-oriented programming in JavaScript. Share it for your reference, as follows:
1. Three ways to create objects:
The first construction method: new Object
var a = new Object();ax = 1, ay = 2;
The second construction method: object direct measurement
var b = { x : 1, y : 2 };The third construction method: define type
function Point(x, y){ this.x = x; this.y = y;}var p = new Point(1,2);2. Access the object
Access the properties of the object
Bracket notation: hero['name']. ,
Point notation: hero.name.
If the accessed property does not exist, undefined will be returned.
Methods to access objects
Add a pair of brackets after the method name: hero.say().
An access method like access attribute: hero['say']().
3. Delete attributes and methods
//Create an empty object var hero = {};//Add attributes and methods to hero.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 hero object delete hero.name;//Test alert(hero.sayName()); //output hello undefined4. Use this value
//Create an empty object var hero = {};//Add attributes and methods to hero object hero.name = "javascript";hero.value = "helloworld";hero.sayName = function(){return "hello " + this.name;};//Test alert(hero.name); //output javascripttalet(hero.sayName()); //output hello javascriptSummarize:
① This here actually refers to "this object" or "current object".
② The usage of this is a problem for most people. So it is not recommended to use too much!
5. Built-in objects
Built-in objects can be roughly divided into three groups:
① Data encapsulation class objects—including Object, Array, Boolean, Number and String. These objects represent different data types in JavaScript, and all have their own different typeof return values, as well as undefined and null states.
② Tool-class objects - including objects used to provide traversals, such as Math, Date, RegExp, etc.
③ Error class objects - including general error objects and various other more special error class objects. They can help us correct the working state of the program when certain exceptions occur.
6.Object object
Object is the parent object of all objects in javascript, which means that all objects are inherited from the Object object.
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();For example 1:
//Invert 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 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 print alert(arr.toString());8.String object
Differences between String objects and basic string types:
var str = "hello";var obj = new String("world");alert(typeof str); //typeof stringalert(typeof obj); //typeof objectFor example 1:
//Example of determining whether a string contains a specified string //Define two strings to be judged var str = "abcdefg";var substr = "efg";/** Define the function to judge whether a string contains a specified string * * First parameter: the string to be judged * * Second parameter: the string to be judged */function sub(str,substr){//Define the string to be judged var string = new String(str);//Intercept the judged string var result = string.substr(str.indexOf(substr),substr.length);/** Determine whether the intercepted string is empty * * is empty, indicating that the specified string does not contain the specified string * * Not empty, indicating that the specified string */if(result==substr){return true;}else{return false;}}alert(sub(str,substr));9. Prototype
The function itself is also an object containing methods and properties. Now what we want to study is another property of the function object - prototype.
Add methods and properties using prototypes
Rewrite prototype properties using its own properties
Extend built-in objects
Add methods and properties using prototypes
Below is to create a new function object and set 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 javascriptAdd some properties 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: 100The above method can also be done like this:
Hero.prototype = { price : 100, rating : 3, getInfo : function(){ return "Rating: " + this.rating + " , Price: " + this.price; }};Rewrite prototype properties using its own properties
What should I do if the object's own attributes are the same as the prototype attribute? The answer is that the object's own attributes have higher priority than the prototype attributes.
function Hero(){ this.name = "jscript";}Hero.prototype.name = "javascript";var hero = new Hero();alert(hero.name); //output jscriptdelete hero.name;alert(hero.name); //output javascriptExtend built-in objects
//Add a function to judge for the prototype Array object Array.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(a.inArray("red")); //truealert(a.inArray("yellow")); //false10. Inheritance
If both classes are of the same instance type, then there are some relationships between them. We call the generalized relationship between types of the same instance "inheritance".
The inheritance relationship contains at least three meanings:
① Instances of subclasses can share methods of parent classes.
② Subclasses can override the parent class's methods or extend new methods.
③ Subclasses and parent classes are both "types" of subclass instances.
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 formulated by the ECMAScript standard.
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 created directly in the prototype property of the B object, and does not extend the original prototype of these objects.
A new entity is created through new A ( ) and then used to overwrite the prototype of the object.
Javascript is a language that relies entirely on objects, and there is no concept of class.
Therefore, it is necessary to directly create an entity with new A ( ) before the relevant inheritance work can be completed through the properties of the entity.
After completing such inheritance implementation, any modification, rewriting or deletion of A ( ) will not affect B ( ).
Inherited from the 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 = 18;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 copy function extendCopy(p){ var z = {}; //Define an empty object z for(var i in p){ //var i =0 ; i < p.length ; i++ z[i] = p[i]; //If you are treated as an array, you can understand} //uber attribute: Use p as the parent of z and point z to the prototype of p z.uber = p; return z;}//Define object a, but object a is not a function object var a = { name : "a", toStr : function(){return this.name;}}//Define 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 , 18PS: Many code layouts in the tutorial are not standardized. Here are a few javascript code formatting and beautification tools for everyone to use:
JavaScript code formatting tool:
http://tools.VeVB.COM/code/js
JavaScript code beautification/compression/formatting/encryption tools:
http://tools.VeVB.COM/code/jscompress
jsmin online js compression tool:
http://tools.VeVB.COM/code/jsmincompress
For more information about JavaScript, please check this site's special topics: "Javascript object-oriented tutorial", "Summary of json operation skills in JavaScript", "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging skills", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques" and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.