09d Javascript
09d Javascript
09d Javascript
By Effie Nadiv
Edited by permission from author by Amir Kirsh
Based on work of
Douglas Crockford
Overview
History
Language
Advanced Features
Platforms
Standards
Style
Question 1
alert("3" == 3);
alert(3 === "3");
alert(+"3" == "3");
alert(3 === +"3");
Question 2
var a = 1;
var o = {
a: 2,
test: function () {
var a = 3;
return this.a;
}
};
alert(o.test());
alert((o.test = o.test)());
Question 3
var o = {
x: 6,
valueOf: function(){
return this.x + 2;
},
toString: function(){
return this.x.toString();
}
};
alert(o);
alert(o < "7");
Question 4
alert(a = (2, 9 - 3) * 3);
Question 5
var x = 5,
o = {
x: 10,
test: function(){
var x = 8;
setTimeout(function(){
alert(this.x);
}, 10);
}
};
o.test();
Question 6
var n1 = "11",
n2 = "3";
Prototypal inheritance
Lambda
Values
Numbers
Strings
Booleans
Objects
null
undefined
Numbers
Only one number type
No integers
64-bit floating point
IEEE-754 (aka “Double”)
Does not map well to common understanding of
arithmetic:
0.1 + 0.2 = 0.30000000000000004
NaN
Special number: Not a Number
Result of undefined or erroneous operations
Toxic: any arithmetic operation with NaN as an
input will have NaN as a result
NaN is not equal to anything, including NaN
Number function
Number(value)
parseInt("08") === 0
parseInt("08", 10) === 8
/*
slashstar
block
comment
*/
Operators
Arithmetic
+ - * / %
Comparison
== != < > <= >=
Logical
&& || !
Bitwise
& | ^ >> >>> <<
Ternary
?:
+
Addition and concatenation
If both operands are numbers,
then
add them
else
convert them both to strings
concatenate them
'$' + 3 + 4 = '$34'
+
Unary operator can convert strings to numbers
+"42" = 42
Also
Number("42") = 42
Also
parseInt("42", 10) = 42
+"3" + (+"4") = 7
/
Division of two integers can produce a non-integer
result
10 / 3 = 3.3333333333333335
== !=
Equal and not equal
}
For statement
Iterate through all of the members of an object:
}
}
Switch statement
Multiway branch
throw {
name: exceptionName,
message: reason
};
Try statement
try {
...
} catch (e) {
switch (e.name) {
case 'Error':
...
break;
default:
throw e;
}
}
Try Statement
The JavaScript implementation can produce these
exception names:
'Error'
'EvalError'
'RangeError'
'SyntaxError'
'TypeError'
'URIError'
With statement
Intended as a short-hand with (o) {
foo = null;
Ambiguous }
Error-prone Instead
o.foo = null;
Don't use it
Function statement
function name(parameters) {
statements;
}
Var statement
Defines variables within a function.
Types are not specified.
Initial values are optional.
var name;
var nrErrors = 0;
var a, b, c;
Scope
In JavaScript, {blocks} do not have scope.
"goto" "Jail"
"grade" "A"
"level" 3
myObject[name] = value;
Object Methods
All objects are linked directly or indirectly to
Object.prototype
All objects inherit some basic methods.
None of them are very useful.
hasOwnProperty(name)
Is the name a true member of this object?
No copy method.
No equals method.
Object Construction
All three expressions below have exactly the same
result, creating a new empty object:
(2) {}
(3) object(Object.prototype)
delete myObject[name];
Arrays
• Array inherits from Object.
• Indexes are converted to strings and used as
names for retrieving values.
• Very efficient for sparse arrays.
• Not very efficient in most other cases.
• One advantage: No need to provide a length or
type when creating an array.
length
Arrays, unlike objects, have a special length member.
array.splice(number, 1)
delete myArray[1];
myArray.splice(1, 1);
function foo() {
alert("foo was invoked!");
}
foo();
(function foo() {
alert("foo was invoked!");
}());
(function() {
alert("Anonymous function was invoked!");
}());
(function() {
alert(arguments.callee + " was invoked!");
}());
function foo() {}
expands to
the global
function
object
the new
constructor
object
arguments
When a function is invoked, in addition to its
parameters, it also gets a special parameter
called arguments.
It is an array-like object.
String.prototype.trim = function () {
return this.replace(
/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
supplant
var template = '<table border="{border}">' +
'<tr><th>Last</th><td>{last}</td></tr>' +
'<tr><th>First</th><td>{first}</td></tr>' +
'</table>';
var data = {
first: "Carl",
last: "Hollywood",
border: 2
};
mydiv.innerHTML = template.supplant(data);
supplant
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' ?
r : a;
}
);
};
typeof
The typeof prefix operator returns a string identifying the
type of a value.
type typeof
object 'object'
function 'function'
array 'object'
number 'number'
string 'string'
boolean 'boolean'
null 'object'
undefined 'undefined'
Built-in Type Wrappers
Java has int and Integer, two incompatible
types which can both carry the same value
with differing levels of efficiency and
convenience
JavaScript copied this pattern to no advantage.
Avoid it.
Avoid new Boolean()
Avoid new String()
Avoid new Number()
Augmentation
We can directly modify individual objects to give
them just the characteristics we want.
myNewObject
myOldObject
"name" "Jack B. Nimble"
"goto" "Jail"
"grade" "A"
"level" 3
“Object Linkage”
myNewObject.name = "Tom Piperson";
myNewObject.level += 1;
myNewObject.crime = 'pignapping';
"level" 4
"crime" "pignapping"
"goto" "Jail"
"grade" "A"
"level" 3
Confession
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
Inheritance
Object Linkage provides simple inheritance.
function hoozit(id) {
var that= gizmo(id);
that.test = function (testid) {
return testid === this.id;
};
return that;
}
12/13/23 JavaScript Objects 121
(global) Object
The object that dares not speak its name.
http://twiki.corp.yahoo.com/view/Devel/TheYAHOOObject
Encapsulate
Function scope can create an encapsulation.
http://javascript.crockford.com/code.html
Semicolon insertion
When the compiler sees an error, it attempts to replace
a nearby linefeed with a semicolon and try again.
Good: [1, 2, 3]
Bad: [1, 2, 3,]
Required Blocks
Good:
if (a) {
b();
}
Bad:
if (a) b();
Forbidden Blocks
Blocks do not have scope in JavaScript.
http://www.JSLint.com/
The JavaScript Programming
Language
Douglas Crockford
crock@yahoo-inc.com
produce.yahoo.com/crock/javascript.ppt
Exercise1
Define a function max() that takes two numbers
as arguments and returns the largest of them.
Use the if-then-else construct available in
Javascript.
Exercise1 - Solution
function max (num1, num2){
if (num1 > num2){
return num1;
} else {
return num2;
}
}
function max (num1, num2){
if (num1 > num2){
return num1;
}
return num2;
}
function max (num1, num2){
return num1 > num2 ? num1 : num2;
}
Exercise2
Define a function max() that takes any numbers
as arguments and returns the largest of them.
Exercise2 - Solution
function max (){
var result = arguments[0],
i;