JS Notes Enhanced Version 3

Source: Internet
Author: User
Tags ming hasownproperty

JS Object-oriented and component development JS Object-oriented: 1. What is object-oriented programming to write code with the object's mind is object-oriented programming .Process Style notationObject-oriented notationwe've been working on objects .Arrays Array Time Datevar date = new Date ();var arr = new Array ();//[]//We bring the system to its own object, called the system objectfeatures of object-oriented programming (OOP)abstraction: Seizing the core issueEncapsulation: Methods can only be accessed through objectsInheritance: Inheriting new objects from existing objectsPolymorphism : Different forms of multiple objects 2, the composition of the object methods (behaviors, actions)--functions: process, dynamicProperties--variables: state, static var arr = [];arr.number = 10;//The variables below the object: Properties called Objectsarr.test = function () {///object: Method called Objectalert (123);}; arr.test ();//123 3. Creation of the first object-oriented program adding properties and methods to an objectObject ObjectsThis pointcreate two objects: Too many duplicate codes //var obj = {};var obj = new Object ();//Create an empty objectobj.name = ' xiaoming ';//Propertiesobj.showname = function () {//Method //alert (obj.name);alert (this.name);//This is pointing to obj }; obj.showname ();////Xiao Ming 4. Factory mode //Factory mode: Encapsulation function in object-oriented function Createperson (name) {
//1. raw var obj = new Object ();//2. Machining Obj.name = Name;obj.showname = function () {alert (this.name);};/ /3. Exit return obj;
} var p1 = Createperson (' xiaoming ');p 1.showName (), var p2 = Createperson (' Xiao Qiang ');p 2.showName ();5. References to Objectsvar a = 5;var b = a;b + = 3;alert (b); 8alert (a); 5 base type: When assigning a value just copy the value of var a = [1,2,3];var B = A;b.push (4); alert (b); [1,2,3,4]alert (a); [1,2,3,4] Object type: Assignment is not only a copy of the value, but also a reference to the passing of var a = [1,2,3];var b = A;b = [1,2,3,4]; b again takes up a memory address, and the original unrelated alert (b); [1,2,3,4]alert (a); [5;var] var a = b = 5;alert (A = = B); Basic type: The same value can be var a = [1,2,3];var b = [1,2,3];alert (A = = B); False//Object type: The value and the reference are the same. var a = [1,2,3];var B = A;alert (a==b); True6, the factory method, the structure function:Initial capitalization, new keyword extraction, this is pointing to the newly created object when new calls a function: This is the object that is created in the function, and the return value of the function is directly the this (implicitly returned) constructor: The function called after new, The function that is used to create the object, called the constructor//Createperson () constructor: function Createperson (name) {//Omit new object and the last return obj this.name = name; This.showname = function () {alert (this.name);}; } var p1 = new Createperson (' xiaoming ');p 1.showName (), var p2 = new Createperson (' Xiao Qiang ');p 2.showName (); Alert (P1.showname = = P2.showname); False, although the value is the same, but the reference memory address is different: object references, wasted memory7. Prototype-prototypePrototype: Overrides an object method, allowing the same method to exist in memory. is to rewrite the common methods or properties under the object, so that the common method or property in memory to have a copy (improve performance) prototype: CSS class, can be reused, but the priority is not a style high normal method: CSS style, can not be reused, high priority is the prototype can be reused, but first There is no normal method for high level. var arr = [];arr.number = 10; Array.prototype.number = 20; alert (Arr.number); 10 General method: var arr = [1,2,3,4,5];var arr2 = [2,2,2,2,2]; Arr.sum = function () {var result = 0;for (var i=0;i<this.length;i++) {result + = This[i];} return result; };arr2.sum = function () {var result = 0;for (var i=0;i<this.length;i++) {result + = This[i];} return result; }; Alert (Arr.sum ()); 15alert (Arr2.sum ()); 10 prototype method: var arr = [1,2,3,4,5];var arr2 = [2,2,2,2,2]; Array.prototype.sum = function () {var result = 0;for (var i=0;i<this.length;i++) {result + = This[i];} return result;}; Alert (Arr.sum ()); 15alert (Arr2.sum ()); 108, the prototype of Factory mode: Object-oriented writing:Prototype prototype: To be written under the constructor function Createperson (name) {this.name = name;} CreatePerson.prototype.showName = function () {alert (this.name);}; var p1 = new Createperson (' xiaoming ');p 1.showName (), var p2 = new Createperson (' Xiao Qiang ');p 2.showName (); Alert (P1.showname = = P2.showname);   True summarizes object-oriented notation: constructor plus attribute, prototype Plus method function constructor (parameter) {this. property = parameter;} constructor. prototype. method = function () {...}; Calling notation: var object 1 = new constructor (); Object 1. Method ();9. Object-oriented examples:Principle: 1) First write the common writing, and then change to object-oriented notation 2) Common method Variant 3) Try not to appear function nesting function 4) can have a global variable 5) in the onload is not an assignment of statements into a separate function Change to Object-oriented: 1) global variable is attribute 2) function is method 3) Create object in onload 4) change this to point to question 5) event EV is put into the event function: var ev = EV | |    Window.event;return false; Example: Object-oriented tab: First step: Common method: <script> window.onload = function () {
var oparent = document.getElementById (' Div1 '); var ainput = oparent.getelementsbytagname (' input '); var adiv = Oparent . getElementsByTagName (' div '); for (Var i=0;i<ainput.length;i++) {Ainput[i].index = I;ainput[i].onclick = function () {
For
(var i=0;i<ainput.length;i++) {
ainput[i].classname = ';
adiv[i].style.display = ' none ';
}
this.classname = ' active ';
adiv[this.index].style.display = ' block ';
};
} }; </script>  Second Step: First variant: Try not to appear function nested functions can have global variables put in the onload is not the assignment of statements into a separate function    < Script> var oparent = Null;var Ainput = Null;var Adiv = Null; window.onload = function () { oParent = Docu Ment.getelementbyid (' Div1 '); ainput = oparent.getelementsbytagname (' input '); Adiv = Oparent.getelementsbytagname (' Div ');  init ();  }; function init () {for (Var i=0;i<ainput.length;i++) {Ainput[i].index = I;ainput[i] . onclick = Change;}}  function Change () {for (Var i=0;i<ainput.length;i++) {ainput[i].classname = '; adiv[i].style.display = ' None ';} This.classname = ' active '; adiv[this.index].style.display = ' block ';}  </script>   Third Step:  global variable is the property function is the method onload in the creation of object change this point to the problem    <script>  window.onload = function () { var t1 = new tab (' Div1 '); T1.init (); T1.autoplay ();  var t2 = new Tab (' Div2 '); T2.init (); T2.autoplay ();  }; function Tab (id) {this.oparent = document.getElementById (id); this.aInput =This.oParent.getElementsByTagName (' input '); this.adiv = This.oParent.getElementsByTagName (' div '); this.inow = 0;}  tab.prototype.init = function () {var this = This;for (var i=0;i<this.ainput.length;i++) {This.ainput[i].index = I;this.ainput[i].onclick = function () {this.change (this);};};  tab.prototype.change = function (obj) {for (Var i=0;i<this.ainput.length;i++) {this.ainput[i].classname = '; This.adiv[i].style.display = ' None ';} Obj.classname = ' active '; this.adiv[obj.index].style.display = ' block ';};  tab.prototype.autoplay = function () { var this = This;setinterval (function () { if (This.inow = = this.ainput.length-1) {this.inow = 0;} else{this.inow++;}  for (var i=0;i<this.ainput.length;i++) {this.ainput[i].classname = '; This.adiv[i].style.display = ' None ';} This.ainput[this.inow].classname = ' active '; This.adiv[this.inow].style.display = ' block ';  },2000); }; </script>  10, Packaging objects: JS prototype-based programs, system objects are also based on the prototype programTry not to modify or add system objects the following methods and property primitives have their own wrapper objects: the String number Boolean base type will find the corresponding wrapper object type, then wrap the object to give all the properties and methods to the base type, and then wrap the object to disappear Var str = ' Hello '; String.prototype.lastValue = function () {return This.charat (this.length-1);}; Alert (Str.lastvalue ()); o var str = ' Hello '; Str.number = 10; After the object is created, the wrapper object disappears immediately alert (str.number); New objects created by undefined 11. Prototype ChainPrototype chain: The connection between the instance object and the prototype is called the outermost of the prototype chain: The Object.prototype object invokes the property in the constructor, and it is searched along the prototype chain to the prototype prototype of the object, if not, Find function Aaa () {this.num = 10;//Priority Highest}aaa.prototype.num = 20, along the outermost prototype chain to Object.prototype; Priority second Object.prototype.num = 30; Priority last var a1 = new Aaa (); alert (a1.num);12, hasOwnProperty: See is not the object itself below the propertiesvar arr = [];arr.num = 10; Array.prototype.num2 = 20; Alert (arr.hasownproperty (' num ')); True//is only an attribute in Arr, the rest of the array object has no alert (arr.hasownproperty (' num2 ')); False//Array object in prototype properties, all arrays have this attribute alert (Arr.hasownproperty = = Object.prototype.hasOwnProperty); True//This property is on the outermost object prototype13. Constructor: View the constructor of an objectfunction aaa () {} var a1 = new aaa (); alert (a1.constructor); AAA var arr = [];alert (arr.constructor = = = Array); True function aaa () {}aaa.prototype.constructor = AAA; Each function will have, is automatically generated Aaa.prototype.constructor = Array; Modified the object's constructor to avoid this function Aaa () {} Aaa.prototype.name = ' xiaoming '; Aaa.prototype.age = 20; var a1 = new Aaa (); alert (a1.constructor);   If the properties of the AAA are written in JSON, then the A1 constructor is not AAA, but the JSON object, that is, Objectaaa.prototype = {constructor:aaa,name: ' Xiaoming ', age:20}; function Aaa () {} Aaa.prototype.name = 10; Aaa.prototype.constructor = AAA; for (Var attr in Aaa.prototype) {//cannot traverse the JS built-in property, only traverse to Namealert (attr);}14. instanceof: Is there any relationship between the object and the constructor on the prototype chain ?Custom Object Function aaa () {} var a1 = new aaa (); Alert (A1 instanceof Object); True//system built-in object var arr = []; Alert (arr instanceof Array); True15. ToString ():ToString (): The system objects are all self-bringing, and do not need to be searched by the prototype chain. The objects you write are all found under object through the prototype chain. var arr = [];alert (arr.tostring = = Object.prototype.toString); False/function aaa () {}var A1 = new AAA (); alert (a1.tostring = = Object.prototype.toString); True toString (): Turns the object into a string var arr = [n/a]; Array.prototype.toString = function () {return this.join (' + ');}; Alert (arr.tostring ()); ' 1+2+3 ' toString (): binary conversion var num = 255;alert (num.tostring (16)); ' FF '//255 turns into 16 binary using ToString to make the type of judgment: (recommended) var arr = []; Alert (Object.prototype.toString.call (arr) = = ' [Object Array] '); ' [Object Array] ' determines the type of constructor and instanceof in the IFRAME without alert (arr.constructor = = Array); Falsealert (arr instanceof Array); False16. Inheritance  Inheritance: On the basis of the original object, slightly modified to get a new object. Does not affect the functionality of the original object.   Subclasses do not affect the parent class, subclasses can inherit some of the functionality of the parent class (code reuse)  1) copy inherits the inheritance of the:  property: The inheritance of calling the constructor of the parent class call  method: For in: Copy Inheritance (jquery also takes copy inheritance ex Tend)  function Createperson (name,sex) {//parent class this.name = Name;this.sex = sex;} CreatePerson.prototype.showName = function () {alert (this.name);};  var P1 = new Createperson (' xiaoming ', ' Male ');//p1.showname ();   function Createstar (name,sex,job) {//subclass   Createperson.call (This,name,sex); Inherit call change this point to object  this.job = job; } //cannot be assigned with object, Createstar.prototype = Createperson.prototype; All point to the same memory address, change one, and the other will change  extend (Createstar.prototype, Createperson.prototype);  CreateStar.prototype.showJob = function () {}; var P2 = new Createstar (' Huang Xiaoming ', ' Male ', ' actor ');  p2.showname ();   function Extend (OBJ1,OBJ2) {//Take all non-object properties of the parent class to subclass for (Var attr in obj2) {obj1[attr] = obj2[attr];}} &NBSP;&NBSP;&NBSP;&NBSP;2) class inheritance:  class: JS is not the concept of class, JS in the constructor function as the class   to do attributes and methods of inheritance, to separate inheritance, to avoid the sub-object modification between the properties of mutual influence   Properties of the followingcall : The constructor of the calling parent class inherits from the method:   function Aaa () () {//parent class this.name = [N/a] with constructor (class) inheritance;} Aaa.prototype.showName = function () {alert (this.name);};   function Bbb () {//subclass, Inheritance of attributes  aaa.call (this);  } //method inheritance var F = function () {}; F.prototype = Aaa.prototype; Only inherited methods Bbb.prototype = new F (); Bbb.prototype.constructor = BBB; Fix point to problem  var B1 = new Bbb () B1.name.push (4); alert (b1.name); [1,2,3,4] var b2 = new BBB (); alert (b2.name);//[1,2,3]   3) prototype inheritance:  implement object-inheriting objects with prototypes  var a = {name: ' Xiao Ming '}; var b = cloneobj (a);  b.name = ' Xiao Qiang ';  alert (b.name);//Xiao Qiang alert (a.name);//Xiao Ming  function Cloneobj (obj) { var F = function () {}; f.prototype = Obj; return new F (); }   Copy inheritance: General-purpose You can   class inheritance with new or no new: New constructor   prototype inheritance: Objects without new  17. Component development: Multiple groups of objects, like the relationship between brothers (a form of code reuse)Separate the configuration parameters, methods, events, and objects into an object-oriented, in-depth application (UI component, functional component)18, custom events: mainly with the function, is to let the function can have some characteristics of the eventWindow.addeventlistener (' Show ', function () {alert (1);},false); Window.addeventlistener (' Show ', function () {alert (2) ;},false); Window.addeventlistener (' Show ', function () {alert (3);},false); Show (); Proactively triggering custom events

JS Notes Enhanced Version 3

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.