-
2007-08-02
Details of the Object Model - [JavaScript]
Details of the Object Model
1.Class-Based vs. Prototype-Based Languages
Class-based object-oriented languages, such as java and C++, are founded on the concept of two distinct entities:class and instances;\
A prototype-based language, such as Javascript, does not make this distinction: It simply has object. A prototype-based language has the notion of a prototypical object. An object used as a template from which to get initial properties for a new object. Any object can specify its own properties, either when you create it or run time. In addition, any object can be associated as the properties for another object, allowing the second object to share the first object’s properties.
Javascript does not have a class definition separate from the constructor.
Javascript implements inheritance by allowing you to associate a prototypical object with any constructor function..
2.Adding and Removing Properties
In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You can not change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.
Prototype-based(javascript)
Ø All objects are instances;
Ø Define and create a set of objects with constructor functions.
Ø Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Ø Inherit properties by following the prototype chain.
Ø Can add or remove properties dynamically to individual object or to entire set of objects.
3.the Employee Example
the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In javascropt, instance does not have this technical meaning because javascript does not have this difference between class and instances, However, in talking about javascript, instance can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer.
4. inheriting Properties
mark = new WorkerBee;
when JS sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly set the value of the projects property, and implicitly set the value of the internal _proto_property to the value of WorkerBee.prototype. The _proto_property determines the prototype chain used to return property vaules. Once these properties are set, javascript returns the new object and the assignment statement sets the variable mark to that object.
This process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. When you ask for the value of a property, javascript first checks to see it the value exists in that object. If it does, that value is returned. If the values is not there locally, javascript checks the protoytype chain(using the _proto_property). If an object in the prototype chain has a value for the prototype, that value is returned. If no such prototype is found, javascript says the object does not have the property. In this way, the mark object has the following properties and values.
Mark.name = “”
Mark.dept = “general”;
Mark.projects = [];
5. Adding Properties
In javascript, you can add properties to any object at run time.
Mark.bonus = 3000;
Now, the mark object has a bonus property, but no other workerBee has this property.
If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement.
Employee.prototype.specialty = “none”;
6. More Flexible Constructors
Jane = new Engineer(“belau”);
Jane’s properties are now:
Jane.name = “”;
Jane.dept = “engineering”;
Jane.projects = [];
Jane.machine = “belau”;
Notice that with these definitions, you can not specify an initial value for an inherited property such as name.
// Employee Class
function Employee(name, dept){
alert("Employee 1");
this.name = name || "";
this.dept = dept || "general";
alert("Employee 2");
}
// WorkerBee Class
function WorkerBee(name, dept, projs){
alert("WorkerBee1");
this.base = Employee;
alert("WorkerBee2");
this.base(name, dept);//调用基类的构造函数
alert("WorkerBee3");
this.projects = projs || [];
alert("WorkerBee4");
}
alert("WorkerBee prototype1");
WorkerBee.prototype = new Employee;//调用类的构造函数
alert("WorkerBee prototype2");
function Engineer (name, projs, mach) {
alert("Engineer 1");
this.base = WorkerBee;
alert("Engineer 2");
this.base(name, "engineering", projs);
alert("Engineer 3");
this.machine = mach || "";
alert("Engineer 4");
}
alert("Engineer prototype1");
Engineer.prototype = new WorkerBee;//调用类的构造函数
alert("Engineer prototype2");
function BtCommand()
{
alert("1");
var en = new Engineer("Doe", "navigator", "belau");
alert("2");
}
当启动firefox浏览器时
//当遇到new时 就调类的构造函数
1 workerbee prototype1
2 Employee1
3 Employee2
4 workerbee prototype2
1.Engineer prototype1
2.WorkerBee1
3.workerBee2
4.Employee1 ->Employee2//在this.base(name, dept)调用基类的构造函数
5.WorkerBee3
6.WorkerBee4
7.Engineer prototype2
当点击按钮时
1.engineer1
2.Engineer2
3.WorkerBee1->WorkerBee1->WorkerBee2->Employee1->Employee2->WorkerBee3->WorkerBee4
4.Engineer3
5.Engineer4
7. Local versus Inherited Values
When you access an object property, javascript performs these steps, as described below:
Ø Check to see if the value exists locally. If it does , return that value.
Ø If there is not a local value, check the prototype chain(using the _proto_).
Ø If an object in the prototype chain has a value for the specified property, return that value.
Ø If no such property is found, the object does not have the property.
function Employee()
{
this.dept = "general";
}
Employee.prototype.name = "";
function WorkerBee()
{
this.projects = [];
}
WorkerBee.prototype = new Employee;
amy = new WorkerBee;
Employee.prototype.name = "Unknown";
In this case, the name property of amy become "Unknown".As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.
8. Determining instance relationships
You may want to know what objects are in the prototype chainfor an object, so that you can tell from what objects thisobject inherits properties.when you use the new operator with a constructor function to create a new object, javascript set the _proto_property of the new object to the value of the prototype property of the constructor function. you can use instanceof to test the prototype chain.
chris = new Engineer("Pigman", "jsd", "fiji");
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;
function instanceof(object, constructor){
while(object._prototype != null){
if(object == constructor.prototype)
return true;
object = object._proto_;
}
return false;
}
with this definition, the following expression are all true;
instanceof(chris, Engineer);
instanceof(chris, WorkerBee);
instanceof(chris, Employee);
instanceof(chris, Object);
9. Global information in Constructors
var idCounter = 1;
function Employee (name, dept) {
this.name = name || "";
this.dept = dept || "general";
this.id = idCounter++;
}
function Manager (name, dept, reports) {...}
Manager.prototype = new Employee;
function WorkerBee (name, dept, projs) {...}
WorkerBee.prototype = new Employee;
function Engineer (name, projs, mach) {...}
Engineer.prototype = new WorkerBee;
function SalesPerson (name, projs, quota) {...}
SalesPerson.prototype = new WorkerBee;
mac = new Engineer("Wood, Mac");
In this case, by the time the mac object object is created, mac.id is 5, one possible solution involves instead using the following constructor:
function Employee(name, dept)
{
this.name = name || "";
this.dept = dept || "general";
if(name)
this.id = idCounter++;
}
When you create an instance of Employee to use as a prototype,you do not supply arguments to the constructor.
10. No Multiple inheritance
Inheritance of property values occurs at run time by javascript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, javascript cannot dynamically inherit from more than one prototype chain.
-
2007-08-02
Working with Objects - [JavaScript]
Working with Objects
1. using object initializers to create an object
The syntax for an object using an object initializer is
objectName = {property_1:value_1, property_2:value_2,…property_n:value_n};
If an object is created with an object initializer in a top-level script, javascript interpretes the object each time it evaluates an expression containing the object literal. In addition, an initializer used in a function is created each time the function is called. The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.
If(cond) x = {hi:”there”}
myHonda = {color:”Red”, wheels:4, engine:{cylinders:4, size:2}};
2.using a constructor function
Alternatively, you can create an object with these two steps:
@.Define the object type by writing a constructor function.
@.Create an instance of the object with new
Define two classes
function person(name, ege, sex){
this.name = name;
this.age = age;
this.set = sex;
}
rand = new person("Rand MxKinnon", 33, "m");
function car(make, modal, year, owner){
this.make = make;
this.modal = madal;
this.year = year;
this.owner = owner;
}
myCar = new car("Eagle", "Talon", 1993, myCar);
3.Defining Properties for an object
You can add a property to a previously defined object type by using the prototype proterty. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object.
Car.prototype.color = null;
Car1.color = “black”;
4.Defining Methods
You use the following syntax to associate the function with an existing object;
Object.methodname = function_name;
5.Deleting Propertoes
You can remove a property by using the delete operator.
Myobj = new Object;
Myobj.a = 5;
Myobj.b = 12;
//removes the a property, leaving myobj with only the b property.
Delete myobj.a;
6. predefined core Objects
6.1 Array Object
An array is an ordered set of values that you refer to with a name and an index.
Creating an Array
Ø arrayObjectName = new Array(element0, element1, element2,...elementN);
Ø arrayObjectName = new Array(arrayLength);
Array literals are also Array objects
coffees = ["French Roast","Columbian", "Kona"]
Array Methods
Ø concat
Ø jion
Ø pop
Ø push
Ø reverse
Ø shift
Ø slice
Ø splice
6.2 Boolean Object
6.3 Date Object
Ø "set" methods, for setting date and time values in Date objects.
Ø "get" methods, for getting date and time values from Date objects.
Ø "to" methods, for returning string values from Date objects.
Ø parse and UTC methods, for parsing Date strings.
*** Function Object
To Create a Function object:
functionObjectName = new Function([arg1, arg2,...argn], functionBody);
functionBodyis a string specifying the JavaScript code to be compiled as the function body.var setBGColor = new Function("document.bgColor='antiquewhite'");
var colorChoice = "antiquewhite";
if(colorChoice == "antiquewhite"){setBGColor()}
you can assign the function to an event handler in either of the following ways:
Ø document.form.colorButton.onclick = setBGColor;
Ø <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color" onClick="setBGColor()">
6.5 Math Object
6.6 Number Object
6.7 RegExp Object
6.8 String Object
s1 = "foo" //creates a string literal values2 = new String("foo") //creates a String objectYou can call any of the methods of theStringobject on a string literal value—JavaScript automatically converts the string literal to a temporaryStringobject, calls the method, then discards the temporaryStringobject. You can also use theString.lengthproperty with a string literal -
2007-08-02
Function - [JavaScript]
Function
1. Defining Functions
All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. However, if you pass an object as a parameter to a function and the function changes the object’s properties, that change is visible outside the function, as shown in the following example:
function myFunc(theObject) {theObject.make="Toyota"}mycar = {make:"Honda", model:"Accord", year:1998};x=mycar.make; // returns HondamyFunc(mycar); // pass object mycar to the functiony=mycar.make; // returns Toyota (prop was changed by the function)2. Using the arguments object
The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows;
Arguments[i];
The total number of arguments is indicated by arguments.length.
function myConcat(separator) {var result = ""; // initialize list// iterate through argumentsfor (var i = 1; i < arguments.length; i++) {result += arguments[i] + separator;}return result;}// returns "red, orange, blue, "myConcat(", ", "red", "orange", "blue");3. predefined function
Ø eval
Ø isFinite
Ø isNaN
Ø ParseInt and parseFloat
Ø Number and string
4. Number and String Functions
D = new Date (430054663215)// The following returns// "Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983"x = String(D)5. escape and unescape Functions
-
2007-08-02
Statements - [JavaScript]
Statements
1. Block statement
Var x = 1;
{
Var x = 2;
}
Alert(x);
This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. In C or Java, the equivalent code would have outputted 1.
2. conditional statemens
2.1. if…else Statement
2.2. switch statement
3. loop statements
3.1. for statement
3.2. do…while statement
3.3. while statement
3.4. label statement
3.5. break statement
3.6. continue statement
3.7. object manipulation statement
3.8. for…in statement
the for…in statement iterates a specified variable over all the properties of an object.
function dump_props(obj, obj_name) {var result = "";for (var i in obj) {result += obj_name + "." + i + " = " + obj[i] + "<br>";}result += "<hr>";return result;}3.9. Exception Handling Statements
3.10. throw statement
// Create an object type UserExceptionfunction UserException (message) {this.message=message;this.name="UserException";}// Create an instance of the object type and throw itmyUserException=new UserException("Value too high");throw myUserException;3.11. try…catch statement
function getCustInfo(name, id, email){var n, i, e;if (!validate_name(name))throw "InvalidNameException"elsen = name;if (!validate_id(id))throw "InvalidIdException"elsei = id;if (!validate_email(email))throw "InvalidEmailException"elsee = email;cust = (n + " " + i + " " + e);return (cust);}try {// function could throw three exceptionsgetCustInfo("Lee", 1234, "lee@netscape.com")}catch (e if e == "InvalidNameException") {// call handler for invalid namesbad_name_handler(e)}catch (e if e == "InvalidIdException") {// call handler for invalid idsbad_id_handler(e)}catch (e if e == "InvalidEmailException") {// call handler for invalid email addressesbad_email_handler(e)}catch (e){// don't know what to do, but log itlogError(e)}openMyFile();try {writeMyFile(theData); //This may throw a error}catch(e){handleError(e); // If we got a error we handle it}finally {closeMyFile(); // always close the resource} -
2007-08-02
Regular Expressions - [JavaScript]
Regular Expressions
1.Creating a regular expression
re = /ab+c/;
re = new RegExp(“ab+c”);
the pattern/chapter (\d+)\.\d* illustrates additional escaped and special characters and indicates that part of the pattern should be remembered. This pattern is found in “Open Chapter 4.3, Paragraph 6” and ‘4’ is remembered.
2.Working with Regular Expressions
Regular expressions are used with the RegExp methods test and exec and with string methods match,replace, search, and split.
Method1.
myRe = /d(b+)d/g;
myArray = myRe.exec("cdbbdbsbz");
method2.
myArray=/d(b+)d/g.exec(cdbbdbsbz);
method3.
myRe=new RegExp(“d(b+)d”,”g”);
myArray=myRe.exec(“cdbbdbsbz”);
<SCRIPT type="text/javascript">myRe = /d(b+)d/g;myArray = myRe.exec("cdbbdbsbz");document.writeln("The value of lastIndex is " + myRe.lastIndex);</SCRIPT><script type="text/javascript">re = /(\w+)\s(\w+)/;str = "John Smith";newstr = str.replace(re, "$2, $1");document.write(newstr);</script>Regular expressions have three optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag.
To include a flag with the regular expression, use this syntax:
Re = /pattern/flags
Re = new RegExp(“pattern”,[“flags”]);
<script type="text/javascript">re = /\w+\s/g;str = "fee fi fo fum";myArray = str.match(re);document.write(myArray);</script>This displays ["fee ", "fi ", "fo "].







