{ x:1, y:2 } // An object initializer
[1,2,3,4,5] // An array initializer
you can use the same identifier naming ruls as in java, though there are some extra rules which can be ignored.
Table 3-2. JavaScript escape sequences
|
|
Sequence
|
Character represented
|
/0
|
The NUL character (
/u0000).
|
/b
|
Backspace (
/u0008).
|
/t
|
Horizontal tab (
/u0009).
|
/n
|
New line (
/u000A).
|
/v
|
Vertical tab (
/u000B).
|
/f
|
Form feed (
/u000C).
|
/r
|
Carriage return (
/u000D).
|
/"
|
Double quote (
/u0022).
|
/'
|
Apostrophe or single quote (
/u0027).
|
//
|
Backslash (
/u005C).
|
/xXX
|
The Latin-1 character specified by the two hexadecimal digits
XX.
|
/uXXXX
|
The Unicode character specified by the four hexadecimal digits
XXXX.
|
/XXX
|
The Latin-1 character specified by the octal digits
XXX, between 1 and 377. Not supported by ECMAScript v3; do not use this escape sequence.
|
Table 3-3. Automatic datatype conversions
|
||||
Value
|
Context in which value is used
|
|||
|
String
|
Number
|
Boolean
|
Object
|
Undefined value
|
"undefined"
|
NaN
|
false
|
Error
|
null
|
"null"
|
0
|
false
|
Error
|
Nonempty string
|
As is
|
Numeric value of string or
NaN
|
TRue
|
String object
|
Empty string
|
As is
|
0
|
false
|
String object
|
0
|
"0"
|
As is
|
false
|
Number object
|
NaN
|
"
NaN
"
|
As is
|
false
|
Number object
|
Infinity
|
"Infinity"
|
As is
|
true
|
Number object
|
Negative infinity
|
"-Infinity"
|
As is
|
TRue
|
Number object
|
Any other number
|
String value of number
|
As is
|
true
|
Number object
|
true
|
"true"
|
1
|
As is
|
Boolean object
|
false
|
"false"
|
0
|
As is
|
Boolean object
|
Object
|
toString( )
|
valueOf( ),
toString( ), or
NaN
|
true
|
As is
|
// First we illustrate copying by value
var n = 1; // Variable n holds the value 1
var m = n; // Copy by value: variable m holds a distinct value 1
// Here's a function we'll use to illustrate passing by value
// As we'll see, the function doesn't work the way we'd like it to
function add_to_total(total, x)
{
total = total + x; // This line changes only the internal copy of total
}
// Now call the function, passing the numbers contained in n and m by value.
// The value of n is copied, and that copied value is named total within the
// function. The function adds a copy of m to that copy of n. But adding
// something to a copy of n doesn't affect the original value of n outside
// of the function. So calling this function doesn't accomplish anything.
add_to_total(n, m);
// Now, we'll look at comparison by value.
// In the following line of code, the literal 1 is clearly a distinct numeric
// value encoded in the program. We compare it to the value held in variable
// n. In comparison by value, the bytes of the two numbers are checked to
// see if they are the same.
if (n == 1) m = 2; // n contains the same value as the literal 1; m is now 2
|
// Here we create an object representing the date of Christmas, 2007
// The variable xmas contains a reference to the object, not the object itself
var xmas = new Date(2007, 11, 25);
// When we copy by reference, we get a new reference to the original object
var solstice = xmas; // Both variables now refer to the same object value
// Here we change the object through our new reference to it
solstice.setDate(21);
// The change is visible through the original reference, as well
xmas.getDate( ); // Returns 21, not the original value of 25
// The same is true when objects and arrays are passed to functions.
// The following function adds a value to each element of an array.
// A reference to the array is passed to the function, not a copy of the array.
// Therefore, the function can change the contents of the array through
// the reference, and those changes will be visible when the function returns.
function add_to_totals(totals, x)
{
totals[0] = totals[0] + x;
totals[1] = totals[1] + x;
totals[2] = totals[2] + x;
}
// Finally, we'll examine comparison by reference.
// When we compare the two variables defined above, we find they are
// equal, because they refer to the same object, even though we were trying
// to make them refer to different dates:
(xmas == solstice) // Evaluates to true
// The two variables defined next refer to two distinct objects, both
// of which represent exactly the same date.
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);
// But, by the rules of "compare by reference," distinct objects are not equal!
(xmas != solstice_plus_4) // Evaluates to true
|
Table 5-1. JavaScript operators
|
||||
P
|
A
|
Operator
|
Operand type(s)
|
Operation performed
|
15
|
L
|
.
|
object, identifier
|
Property access
|
|
L
|
[]
|
array, integer
|
Array index
|
|
L
|
( )
|
function, arguments
|
Function call
|
|
R
|
new
|
constructor call
|
Create new object
|
14
|
R
|
++
|
lvalue
|
Pre- or post-increment (unary)
|
|
R
|
--
|
lvalue
|
Pre- or post-decrement (unary)
|
|
R
|
-
|
number
|
Unary minus (negation)
|
|
R
|
+
|
number
|
Unary plus (no-op)
|
|
R
|
~
|
integer
|
Bitwise complement (unary)
|
|
R
|
!
|
boolean
|
Logical complement (unary)
|
|
R
|
delete
|
lvalue
|
Undefine a property (unary)
|
|
R
|
typeof
|
any
|
Return datatype (unary)
|
|
R
|
void
|
any
|
Return undefined value (unary)
|
13
|
L
|
*,
/,
%
|
numbers
|
Multiplication, division, remainder
|
12
|
L
|
+,
-
|
numbers
|
Addition, subtraction
|
|
L
|
+
|
strings
|
String concatenation
|
11
|
L
|
<<
|
integers
|
Left shift
|
|
L
|
>>
|
integers
|
Right shift with sign extension
|
|
L
|
>>>
|
integers
|
Right shift with zero extension
|
10
|
L
|
<,
<=
|
numbers or strings
|
Less than, less than or equal
|
|
L
|
>,
>=
|
numbers or strings
|
Greater than, greater than or equal
|
|
L
|
instanceof
|
object, constructor
|
Check object type
|
|
L
|
in
|
string, object
|
Check whether property exists
|
9
|
L
|
==
|
any
|
Test for equality
|
|
L
|
!=
|
any
|
Test for inequality
|
|
L
|
===
|
any
|
Test for identity
|
|
L
|
!==
|
any
|
Test for nonidentity
|
8
|
L
|
&
|
integers
|
Bitwise AND
|
7
|
L
|
^
|
integers
|
Bitwise XOR
|
6
|
L
|
|
|
integers
|
Bitwise OR
|
5
|
L
|
&&
|
booleans
|
Logical AND
|
4
|
L
|
||
|
booleans
|
Logical OR
|
3
|
R
|
?:
|
boolean, any, any
|
Conditional operator (three operands)
|
2
|
R
|
=
|
lvalue, any
|
Assignment
|
|
R
|
*=,
/=,
%=,
+=,
-=,
<<=,
>>=,
>>>=,
&=,
^=,
|=
|
lvalue, any
|
Assignment with operation
|
1
|
L
|
,
|
any
|
Multiple evaluation
|
for (variable in object)
for (var prop in my_object) {
Table 6-1. JavaScript statement syntax
|
||
Statement
|
Syntax
|
Purpose
|
break
|
break;
break
label;
|
Exit from the innermost loop or
switch statement or from the statement named by
label
|
case
|
case
expression:
|
Label a statement within a
switch statement
|
continue
|
continue;
continue
label;
|
Restart the innermost loop or the loop named by
label
|
default
|
default:
|
Label the default statement within a
switch statement
|
do/while
|
do
statement
while (
expression);
|
An alternative to the
while loop
|
empty
|
;
|
Do nothing
|
for
|
for (
initialize ;
test ;
increment)
statement
|
An easy-to-use loop
|
for/in
|
for (
variable in
object)
statement
|
Loop through the properties of an object
|
function
|
function
funcname([
arg1[...,
argn]])
{
statements
}
|
Declare a function
|
if/else
|
if (
expression)
statement1
[else
statement2]
|
Conditionally execute code
|
label
|
identifier:
statement
|
Give
statement the name
identifier
|
return
|
return [
expression];
|
Return from a function or return the value of
expression from a function
|
switch
|
switch (
expression) {
statements
}
|
Multiway branch to statements labeled with
case or
default:
|
throw
|
throw
expression;
|
Throw an exception
|
try
|
try {
statements
}
catch (
identifier) {
statements
}
finally {
statements
}
|
Catch an exception
|
var
|
var
name_1 [ =
value_1]
[ ,...,
name_n [ =
value_n]];
|
Declare and initialize variables
|
while
|
while (
expression)
statement
|
A basic loop construct
|
with
|
with (
object)
statement
|
Extend the scope chain (deprecated)
|
Objects and arrays are different interfaces to the same data structure.
To create an object using a constructor function:
1 define the object type by writing a constructor function.
2 create an instance of the object with new.
Note that you can add a new property to an instance at anytime like:
car2.newProperty = newValue;
But note that the new property merely affect the instance car2 not any other instances of the same object type. If you want to add a new property to an object type you should manipulate on the object type.
You can refer a property by name or ordinal index. But if you define a property with a name you may always refer to it by name, and if you define a property with an index you must always refer to it by an index.
Class-based versus prototype-based languages
For class-based languages
there is a distinction between classes and instances.
For prototype-based languages there is not.
They simply have objects.
And there is concept of a
prototype object which used as a template to get initial properties for a new object.
Any object can be the prototype of another object.
Any object can
specify its own properties at any time whether you create it or run it.
In classed-based languages there is a separate fragment of class defining where you can specify constructor methods. A constructor can specify initial values for the instance’s properties and perform other processing appropriate at creation time.
In javascript you define a constructor function to create objects with a particular initial set of properties and values.
Any javascript function can be used as a constructor. You use new operator with a constructor with a constructor function to create to new object.
Inheritance
Javascript implements
inheritance by allowing you to associate a prototypical object with any constructor function. For example, you define the Employee constructor function with some properties. Next, you define the Manager constructor function with its own properties. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then when you create a new Manager, it inherits the properties from the Employee object.
Adding and removing properties
In class-based languages you can’t change the number of properties after your definition. But you can do it in javascript.
Table 8.1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems
There is an example which shows the differences between java and javascript.
to implements the hierarchy above we do in javascript:
what’s more:
Note that
“instance” in javascript does not have the same meaning as in class-based languages. In javascript we talk about “instance” as an object created using particular constructor function. So in the examples above jane is an instance of Engineer.
Note that although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript;
you can use them informally to refer to objects higher or lower in the prototype chain.
The following section shows that how an new object is created in more detail:
Mark = new WorkerBee;
1. In javascript, the new operator
creates a new generic object and javascript
passess this new object as the value of the this keyword to the WorkerBee constructor function.
2. Then the constructor function
sets the value of the new object’s own properties. It also sets an internal
_proto_ property to the value of WorkerBee.prototype. the _proto_ property determines the prototype chain used to return property values.
3. Then javascript returns the new object and sets the mark to the returned object.
4. javascript doesn’t explicitly put values that is herited from the prototype chain. When you ask for the value of a property, javascript will first check to see if the value exists in that object. if not to check from upper level in the prototype chain using the _proto_ property. And so on.
More about adding property
If you add a new property to an object that is used as the prototype for a constructor function, you add that property to all objects that inherit from it. For example,
how to specify initial values to the inherited properties:
for example:
function Engineer (name, projs, mach) {
this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || ""; }
if you create an object like:
jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
then something happen as these steps:
1.
The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
2.
The new operator passes the new object to the Engineer constructor as the value of the this keyword.
3.
The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object. The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
4.
The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.
5.
Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
6.
Upon return from the base method, the Engineer constructor initializes the object's machine property to "
belau
".
7.
Upon return from the constructor, JavaScript assigns the new object to the jane variable.
If you want to change the value of an object property at run time and have the new value be inherited by its descendants, you can’t define the property in the object’s constructor function. Because if you do so, you can see:
function obj1()
{
this.pro=””;
}
function obj2()
{}
obj2.prototype=new obj1;
Now you can see that there is an instance of obj1 assigned to obj2.prototype. It means that there is a local variabl prototype. So the pro property of obj2.prototype exists. If you change the pro of obj1, no affection may be made on obj2. And you can resolve this problem as:
function obj1()
{}
obj1.pro=””;
function obj2()
{}
obj2.prototype=new obj1;
In the case above if you change the pro property of obj1 the pro property inherited by obj2 from obj1 is also changed.
There is an example of prototype chain.
chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
With this object, the following statements are all true:
chris.__proto__ == Engineer.prototype;
chris.__proto__.__proto__ == WorkerBee.prototype; chris.__proto__.__proto__.__proto__ == Employee.prototype; chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; |