The 7 Things I Know About Cyber Security After 25 Years | April 2024
Art of Javascript
1.
2. JavaScript is a lightweight programming
language to add interactivity to HTML
pages.
3. Put
dynamic text into an HTML page.
React to events
Read and write HTML elements
Validate input data
Detect the visitor's browser
Create cookies
4. New in Html 5:
Access new HTML Elements and Events.
Draw using canvas object
Geolocation: get current location position.
Offline Storage
Post message
Multiple Thread
Socket Programming
Offline web application
5. Embedded
in Html.
<script type="text/javascript"><![CDATA[
JavaScript Code
]]></script>
Scripts
can be provided locally or remotely.
<script language="JavaScript” type="text/javascript“
src="http://somesite/myOwnJavaScript.js">
</script>
10. Compatibility Items:
Elements
Attributes
Browser version
Device/Operating system
Detect the visitor's browser
var x = "User-agent header sent: " + navigator.userAgent;
User-agent header sent: Opera/9.80 (Windows NT 5.1)
Presto/2.12.388 Version/12.16
11.
12.
13. var el = document.createElement(“new_el”);
element.appendChild(el);
document.body.appendChild(el);
14. var fragment = document.createDocumentFragment ();
fragment.appendChild(el_1)
fragment.appendChild(el_2)
fragment.appendChild(el_3)
fragment.appendChild(el_4)
document.body.appendChild(fragment);
15. var el = document.getElementById(„Id‟);//single element
if (document.all || document.getElementById) {
...
}
val el = document.get ElementsByClassName(„el‟);//select collection of nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„tagName‟);//select collection of
nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„*‟);//select all tags
val el = document.get ElementsByName(„el‟);//select collection of nodes
el[0] //get the first element
16. var el = document.querySelector(„#Id‟);//select first element
val el = document.querySelector( „.el‟);//select first element
val el = document.querySelectorAll( „.el‟);//select collection of nodes
17. Some
old:
• getElementById
• getElementsByTagNameNot work with object
Some
new:
• getElementsByClassName
Firefox 3, Safari 3, Opera 9.6, IE9
Opera doesn’t match a second-specified class
• querySelectorAll
In Firefox 3.1, Safari 3.1, Opera 10, IE 8
Safari 3.1 had memory out of bounds problems
Safari 3.2 can’t match uppercase characters in quirks mode
21. var el = element.parentNode;
var el = element.childNodes; //Elements + White space
var el = element.children; //Only Elements
var el = element..nextSibling; //next node or null
var el = element..previousSibling; //previous node or null
var el = element..nextElementSibling;
var el = element..previousElementSibling;
22.
23. onabort
- Loading of an image is interrupted
onblur - An element loses focus
onchange - The content of a field changes
onclick - Mouse clicks an object
ondblclick - Mouse double-clicks an object
onerror - An error occurs when loading a
document or an image
onfocus - An element gets focus
onkeydown - A keyboard key is pressed
24. onkeypress
- A keyboard key is pressed or
held down
onkeyup - A keyboard key is released
onload - A page or an image is finished
loading
onmousedown - A mouse button is pressed
onmousemove - The mouse is moved
onmouseout - The mouse is moved off an
element
onmouseover - The mouse is moved over an
element
onmouseup - A mouse button is released
25. onreset
- The reset button is clicked
onresize A window or frame is resized
onselect - Text is selected
onsubmit - The submit button is clicked
onunload - The user exits the page
28.
Bubbling: the event is first captured and handled by the inner most
element and then propagated to outer elements.
Capturing : event is first captured by the outer most element and
propagated to the inner most element.
Only event bubbling model is supported by all the major browsers.
if ( <addEventListener detect> ) {
// W3C DOM Event Model
// Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9
}
else if ( <IE or attachEvent detect> ) {
// Previous IE Event Model code
}
29. To preventing any parent event handlers from being executed.
addEvent(div, 'mouseover', function(ev) {event =
event || window.event // cross-browser event
if (event.stopPropagation) {
// W3C standard variant
event.stopPropagation()
} else {
// IE variant
event.cancelBubble = true
}
});
34. Only
one number type
64 bit floating point
Does not map well to common
understanding of arithmetic
0.1 + 0.2 = 0.30000000000000004
35. Special
number: Not a Number
Result of undefined or erroneous
operations.
Toxic: any arithmetic operation with NaN
will have a NaN as a result.
NaN is not equal anything including NaN
37. parseInt(value,10)
Convert the value into a number.
It stops at the first non-digit character.
The radix (10) should be required
parseInt(“08”) === 0
parseInt(“08”, 10) === 8
42. Default
value for variables and parameters
The value of missing members in objects
function isDefined(value) {
return(typeof value != "undefined");
}
44. Date
new Date() ; //Current date
new Date(year, month, day);
Date.parse('2/6/2009');//wrong will depend on culture
Y2K
Problem
Date.prototype.getRealYear = function()
{
if(this.getFullYear)
return this.getFullYear();
else
return this.getYear() + 1900;
};
45. unordered collection of properties with
arbitrary values
object literal
var obj = { name: "Joe", age: 26 };
setting a property
obj.lastName = "Smith";
retrieving properties
alert(obj.name + " " + obj.lastName);
46. Data structure that associates arbitrary
values with arbitrary strings
property name as an identifier
obj.lastName = "Smith";
property name as a string
obj["lastName"] = "Smith";
for( prop in obj ) {
alert( prop + ": " + obj[prop] );
}
47. Concept of a class does not exist...
... but use a function as a constructor:
function Dog() {};
class “Dog”
var lassie = new Dog(); instance “lassie”
alert(lassie instanceof Dog); // true
48. Because functions are „first-class objects“
we can attach properties:
Class Variables
Dog.SPECIES = "Canis lupus";
Class Methods
Dog.getCount = function() {
return Dog.COUNT;
};
50. Instance
Methods
function Dog(name) {
this.name = name;
this.bark =
function() { alert("Woof!") };
};
var lassie = new Dog("Lassie");
lassie.bark();
51. Global
Scope
• Variables outside of any functions
• Variables inside functions without var
var global1 = 1;
global2 = 2;
function foo() {
global3 = 3;
};
52. Function
Scope
• Variables inside functions declared with var
• Function arguments
function foo(local1) {
var local2 = 2;
};
53. Block
Scope
... but can be faked:
// before block
(function() {
// inside block
})();
// after block
54. function Dog(name) {
var _name = name; // private variable
// privileged method
this.getName = function() {
return _name;
};
};
var lassie = new Dog("Lassie");
alert( lassie.getName() );
55. function Dog(name) {
var _name = name;
// private method
var _fixName = function() {
return _name.toUpperCase();
};
this.getName = function(){
return _fixName();
};
};
56. Nested
functions
Inner function has still access to local
variables even after the outer function
has finished
57. function outer()
{
var count = 1;
function inner() { alert(count++) }
return inner;
}
var myClosure = outer();
myClosure(); // ==> 1
myClosure(); // ==> 2
59. function Pet(name) {
this.name = name;
};
function Dog(name) {
// super(name)
Pet.call( this, name );
this.bark = function() {};
};
Dog.prototype = new Pet;
60. //
old: attach to "this“
function Dog(name) {
this.bark =
function(){ alert("Woof!") };
};
//
new: attach to "prototype"
function Dog(name) {};
Dog.prototype.bark =
function(){ alert("Woof!") };
};
61. Property
values on instance:
local, instance-specific values
Property values on prototype:
read-only default values attaching to the
prototype saves memory, especially for
large numbers of instances
62. Affects
all new instances
Affects all existing instances
Allows modification of existing classes
String.prototype.trim =
function() {
return this.replace(/^s+/, "");
};
alert(" Lassie".trim() );
63. function Dog() {};
Dog.prototype.bark =
function() { alert("Woof!") };
function Bulldog() {};
Bulldog.prototype = new Dog;
Bulldog.prototype.bark = function() {
// super.bark();
Dog.prototype.bark.call(this);
alert("Grrrh!!") };
64. function Pet() {
if(this._id == Pet._id) {
throw new Error("No Pets, please!");
}
}
Pet._id = "Pet";
Pet.prototype._id = "Pet";
var fiffy = new Pet; // Error (intended)
65. But now our code to setup inheritance will
fail:
Dog.prototype = new Pet; // Error :-(
Solution: Do not create an instance of the
actual
superclass just to setup inheritance, use a
dummy:
function Dummy() {};
Dummy.prototype = Pet.prototype;
Dog.prototype = new Dummy;
66. if (typeof very == "undefined") {
very = {};
}
if (typeof very.cute == "undefined") {
very.cute = {};
}
very.cute.Dog = function() {};
var fiffy = new very.cute.Dog;
67. // The Last of the Mohicans
var chingachgook = {
fight : function() {
alert("Woah!");
}
};
chingachgook.fight();
68. function Mohican() {
this.fight = function(){alert("Woah!")}
};
Mohican.getInstance = function() {
if (!this._instance) {
this.instance = new this; }
return this._instance;
};
Mohican.getInstance().fight();
69.
70.
Avoiding Conflicts with Other Libraries ($)
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
71.
use multiple window.onload events with external scripts:
window.onload = init;
function addOnloadEvent(fnc){
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", fnc, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", fnc );
}
else {
if ( window.onload != null ) {var oldOnload = window.onload;
window.onload = function ( e ) {oldOnload( e ); window[fnc]();};
}
else
window.onload = fnc;
}
}
addOnloadEvent(myFunctionName);
72.
Feature-Detect Rather Than Browser-Detect
if (document.getElementById) {
var element = document.getElementById('MyId');
}
else {
alert('Your browser lacks the capabilities required to run this script!');
}
Use Square Bracket Notation
MyObject.property
MyObject."value"+I
(Work)
(not Work)
formref.elements.name[] (not Work)
MyObject["property"] (Work)
MyObject["value"+i] (Work)
formref.elements["name[]"] (Work)
73.
Use onclick In Anchors Instead Of javascript: Pseudo-Protocol
<a href="/" onClick="return validate();">Home</a>
function validate() {
return prompt("Are you sure you want to exit this page?");
}
What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>
74.
Use The Unary + Operator To TypeConvert To Number
function total() {
var theform = document.forms["myform"];
var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
alert(total); // This will alert 3
}
Don't Use HTML Comments In Script Blocks
<script language="javascript">
<!-// code here
//-->
</script>
75.
Avoid Cluttering The Global Namespace
var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7
76.
Model:
organize the application's data layer.
View:
Templates to render HTML data in controllers and inject them into the DOM.
Composed Views: divide the view into small blocks which can be reused or adapted
to different scenarios.
Controller :
A controller is a list of functions that gets called back when the appropriate event
happens.
80. Jquery
The
Dojo Toolkit
The Yahoo! User Interface Library
Prototype (and Script.aculo.us)
MooTools
ExtJS
provides everything you need to build robust
desktop and mobile web apps.
86.
Define local variables
var doc = document;
elem = doc.getElementById(“objId”);
Combine control conditions and control variable changes when using loops
var x = 9;
do { } while( x-- );
87.
Define arrays for HTML collection objects
function array(items) {
try {
return Array.prototype.concat.call(items);
} catch (ex) {
var i = 0, len = items.length, result = Array(len);
while (i < len) { result[i] = items[i];i++; }
return result;
}
}
var divs = array(
document.getElementsByTagName('div') );
for (var i=0l i < divs.length; i++ ) {
var div = document.createElement("div");
document.appendChild(div);
}
88.
Appending DOM elements all at once faster than adding them individually.
var div = document.getElementsByTagName("div");
var fragment = document.createDocumentFragment();
for ( var e = 0; e < elems.length; e++ ) {
fragment.appendChild( elems[e] );
}
for ( var i = 0; i < div.length; i++ ) {
div[i].appendChild( fragment.cloneNode(true) );
}
Change CSS classes not styles
90.
Avoid memory leaks and circular references in your closures
//Classic case for circular references
function foo(e,d) {
$(e).on("click", function() {
//Do something with d
});
}
//Break the cycle!
function foo(e, d) {
$(e).on("click", cbk(d));
}
function cbk (d) {
}
Avoid using eval
Minimize file size
Caching use external file
Deferred execution
97. In
browser (easy) - JSUnit
Browser Control (comprehensive) –
Selenium
http://www.seleniumhq.org/
Simulated (fast) – Env.js
http://www.envjs.com/
98. – Understands JavaScript, hard to
document complex features
http://code.google.com/p/jsdoc-toolkit/
Natural Docs – Can document anything
MVCDoc – Can document anything,
understands some JS.
JSDoc