JavaScript obiektowość WWW 27 kwietnia 2017
Od funkcyjności do obiektowości Wyrażenie regularne DOM Zdarzenia
Obiekty w JS Intuicja Obiekty nie maja przypisanych klas, natomiast maja przypisane konstruktory. Konstruktory z kolei maja prototypy, które sa obiektami i moga definiować właściwości całej klasy obiektów.
Funkcja, prototyp i new 1 function Ninja(){} 2 3 Ninja. prototype. swingsword = function(){ 4 return true; 5 }; 6 7 var ninja1 = Ninja(); 8 assert( ninja1 === undefined) 9 10 var ninja2 = new Ninja(); 11 assert( ninja2 && ninja2. swingsword())
Poszukiwanie właściwości Kolejność przeszukiwania Przeszukiwany jest obiekt. Jeśli w obiekcie nie ma właściwości, to przeszukiwany jest prototyp. Jeśli w prototypie nie ma właściwości, to zwracane jest undefined.
Przeszukiwanie przykład 1 1 function Ninja(){ 2 this.swung = false; 3 this. swingsword = function(){ 4 return!this. swung; 5 }; 6 } 7 8 Ninja. prototype. swingsword = function(){ 9 return this.swung; 10 }; 11 12 var ninja = new Ninja(); 13 14 assert(ninja. swingsword ());
Przeszukiwanie przykład 2 1 function Ninja(){ 2 this.swung = true; 3 } 4 5 var ninja = new Ninja(); 6 7 Ninja. prototype. swingsword = function(){ 8 return this.swung; 9 }; 10 11 assert(ninja. swingsword ()); Właściwości można dopisać do prototypu nawet po utworzeniu obiektu.
Konstruktor Każdy obiekt posiada pole constructor 1 > ninja. constructor 2 function Ninja(){ 3 this.swung = true; 4 } 5 6 > ninja. constructor. prototype. swingsword 7 function(){ 8 return this.swung; 9 };
Jak sprawdzić typ typeof i instanceof, to dwie różne rzeczy. 1 function Ninja(){} 2 var ninja = new Ninja(); 3 assert( typeof ninja == " object"); 4 assert(ninja instanceof Ninja); 5 assert(ninja. constructor == Ninja); 6 7 var ninja2 = new ninja. constructor (); 8 assert( ninja2 instanceof Ninja); Pole constructor można zmienić, zwróćmy uwagę na to, że może być ono funkcja anonimowa.
Dziedziczenie nie działa 1 function Person (){}; 2 Person. prototype. dance = function (){}; 3 4 function Ninja(){}; 5 Ninja. prototype = { 6 dance: Person. prototype. dance 7 }; 8 9 var ninja = new Ninja(); 10 11 assert(ninja instanceof Ninja); 12 assert(!( ninja instanceof Person)); 13 assert(ninja instanceof Object);
Dziedziczenie działa 1 function Person (){}; 2 Person. prototype. dance = function (){}; 3 4 function Ninja(){}; 5 Ninja. prototype = new Person(); 6 7 var ninja = new Ninja(); 8 9 assert(ninja instanceof Ninja); 10 assert(ninja instanceof Person); 11 assert(ninja instanceof Object); 12 assert( typeof ninja. dance == " function");
Modyfikacja wbudowanych typów 1 if (! Array. prototype. foreach) { 2 Array. prototype. foreach = function(fn, callback) { 3 for (var i = 0; i < this. length; i++) { 4 fn.call( callback null, this[i], i, this); 5 } 6 }; 7 8 ["a", "b", "c"].foreach( 9 function( value, index, array) { 10 console.log( value); 11 } 12 );
Wyrażenia regularne 1 var tags = /^( abbr br col img input link \ 2 meta param hr area embed)$/i; 3 function convert(html) { 4 return html.replace (/(<(\w+)[^>]*?)\/>/g, 5 function (all, front, tag) { 6 return tags.test(tag)? 7 all : 8 front + "></" + tag + ">"; 9 }); 10 } 11 assert( convert("<a/>") === "<a></ a>"); 12 assert( convert("<hr/>") === "<hr/>");
Dostęp do drzewa DOM 1 window. onload = function(){ 2 var div = 3 document. getelementsbytagname("div")[0]; 4 div. setattribute(" id"," ninja -1"); #2 5 assert( div. getattribute( id ) === " ninja -1"); 6 div. id = " ninja -2"; 7 assert( div. id === " ninja -2"); 8 div. id = " ninja -3"; 9 assert( div. id === " ninja -3"); 10 assert( div. getattribute( id ) === " ninja -3"); 11 div.setattribute("id","ninja -4"); 12 assert( div. id === " ninja -4"); 13 assert( div. getattribute( id ) === " ninja -4"); 14 }
Właściwości elementu Lista pól Node.childNodes Node.firstChild Node.lastChild Node.parentNode Node.nextSibling Node.previousSibling
Dostęp do drzewa DOM 1 <form id=" testform" action ="/"></ form> 2 <script> 3 window. onload = function(){ 4 var input = document. createelement( input ); 5 input. type = text ; 6 assert( input. type == text ); 7 document. getelementbyid( testform ) 8. appendchild( input); 9 input. type = hidden ; 10 assert( input. type == hidden ); 11 }; 12 </ script >
Style 1 document. getelementbyid( intro ). style. color = 2 #FF0000 ; 3 var mydocument = document; 4 var myintro = mydocument. getelementbyid( intro ); 5 var myintrostyles = myintro. style; 6 myintrostyles.color = # FF0000 ; 7 myintrostyles. padding = 2px 3px 0 3px ; 8 myintrostyles. backgroundcolor = #FFF ; 9 myintrostyles. margintop = 20 px ; 10 myintrostyles.padding -top = 10 em ; 11 // syntax error
Dostęp przez tablicę, innerhtml 1 function changestyle( elem, property, val) { 2 elem.style[ property] = val; 3 } 4 5 var myintro = document. getelementbyid( intro ); 6 changestyle( myintro, color, red ); 7 8 myintro. innerhtml = 9 New content for the < strong > amazing </ strong > + 10 paragraph! ; 11 myintro.innerhtml +=... some more content... ;
Dodawanie elementów 1 var myintro = document. getelementbyid( intro ); 2 3 var sometext = This is the text I want to add ; 4 var textnode = document. createtextnode( sometext); 5 myintro. appendchild( textnode); 6 7 var mynewlink = document. createelement( a ); 8 mynewlink. href = http:// google. com ; 9 mynewlink. appendchild( 10 document. createtextnode( Visit Google )); 11 12 myintro. appendchild( mynewlink);
Zdarzenia Typy zdarzeń Mysz (mousedown, mouseup, click, dblclick, mouseover, mouseout, mousemove) Klawiatura (keypress, keydown, keyup) Form (select, change, submit, reset, focus, blur) Inne (load, resize, scroll, unload)
Rejestracja zdarzeń 1 < button onclick =" return buttonclick()"> 2 Click me!</ button > 3 === albo === 4 <button id="my-button">click me!</button> 5 <script> 6 var myelement = 7 document. getelementbyid( my- button ); 8 function buttonclick() { 9 alert( You just clicked the button! ); 10 } 11 myelement. onclick = buttonclick; 12 </ script >
addeventlistener i removeeventlistener 1 // target. addeventlistener( type, function, usecapture); 2 var myintro = document. getelementbyid( intro ); 3 myintro. addeventlistener 4 ( click, introclick, false); 5 function introclick() { 6 alert( You clicked the paragraph! ); 7 } 1 myintro. removeeventlistener 2 ( click, introclick, false); Kontekst, czyli this jest obiektem na którym zostało wywołane zdarzenie.
Obiekt zdarzenie 1 function myeventhandler(e) { 2 3 // Preventing the default action of an event: 4 if (...) { 5 e. preventdefault (); 6 } 7 // albo 8 if (...) { 9 e. stoppropagation (); 10 } 11 }
Propagacja
Delegacja + IE 1 var mytable = document. getelementbyid( my- table ); 2 3 mytable. onclick = function() { 4 5 e = e window. event; 6 var targetnode = e. target e. srcelement; 7 8 if ( targetnode. nodename. tolowercase() 9 === tr ) { 10 alert ( You clicked a table row! ); 11 } 12 13 }
XHR start 1 // Old compatibility code, no longer needed. 2 if ( window. XMLHttpRequest) { // Mozilla, Safari, IE7 3 httprequest = new XMLHttpRequest (); 4 } else if ( window. ActiveXObject) { // IE 6 and older 5 httprequest = new ActiveXObject(" Microsoft. XMLHTTP") 6 }
XHR 1 < button id=" ajaxbutton" type=" button">make a request 2 <script> 3 (function() { 4 var httprequest; 5 document. getelementbyid(" ajaxbutton"). addeve 6 7 function makerequest() { 8 httprequest = new XMLHttpRequest (); 9 10 if (! httprequest) { 11 alert( Giving up :( Cannot create an XMLHTTP 12 return false; 13 } 14 httprequest. onreadystatechange = alertcontents; 15 httprequest. open( GET, test. html ); 16 httprequest.send(); 17 }
XHR 1 function alertcontents() { 2 if ( httprequest. readystate === XMLHttpRequest.DONE) 3 if ( httprequest. status === 200) { 4 alert( httprequest. responsetext); 5 } else { 6 alert( There was a problem with the request. ); 7 } 8 } 9 } 10 })(); 11 </ script >