function Employee () {
this.name = "";
this.dept = "general";
}
|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
|
| Recommended Links | Tutorials | FAQs | ||||||
| RegEx | WSH | Javascript in Lotus Notes | Netscape Debugger | |||||
| DOM Model | Advanced | Cookies |
Outliners, Contents Generators |
Debugging | History | Humor | Etc |
JavaScript is a very interesting scripting language that has nothing to do with Java. The name was chosen for marketing reasons.
I think that it can be used as a first programming language in high schools instead of Pascal. It also can be (should be) used as Windows scripting language. The current version is ECMA-262 revision 3 (aka JavaScript 1.5.). The most recent implementation of JScript is JScript .NET, which is based on the yet-unfinished version 4 of the ECMAScript standard, and can be compiled for the Microsoft .NET platform. JScript adds several new features to ECMAScript, such as optional static type annotations.
The Javascript interpreters has a unique feature: they can be configured to accept varying language versions (as in language="JavaScriptXXX").
JavaScript is the only mainstream language that uses a prototype-based object-oriented implementation (pioneered in Sun Self language). Just because programming language is object oriented it does not mean that it should support classes. Classes are "Aristotelian model" that does not always help to find similarities is a real word. for example both chess and baseball are games but class model is fruitless to define common properties here.
JavaScript uses a different model called prototype-based programming. Most people use JavaScript without realizing this but this model supports very powerful constructs, like dynamically attaching behavior to built-in objects via .prototype. For example if we define the function Employee as:
function Employee () {
this.name = "";
this.dept = "general";
}
We can create object manager that inherits all properties (slots) of the Employee by using statement Manager.prototype = new Employee.
function Manager () {
this.reports = [];
}
Manager.prototype = new Employee;function WorkerBee () {
this.projects = [];
}
WorkerBee.prototype = new Employee;
Proponents of prototype-based programming argues that the use of abstract classes is not a natural way people thing about objects. People thinks in concrete objects and abstract them, not create abstraction first then try to flesh them into a concrete objects.
JavaScript was developed in 1995 by Brendan Eich at Netscape, now a division of AOL. initial name was Lifescript and it was changes to JavaScript for marketing reasons. As a language JavaScript belongs has nothing to do with Java. It is a scripting language like Perl, TCL, Python, etc. See also NetscapeWorld - JavaScript 1.2's evolution as explained by its creator - May 1997. Here is his own version of events that led to the creation of JavaScript:
I came to Netscape in April 1995, after seven years at Silicon Graphics and three years at MicroUnity Systems Engineering. Netscape was about a year old then and was looking for someone to work on a scripting language or some kind of language inside the browser that could be used to automate parts of a web page or make a web page more dynamic. Java had been around for five years at First Person and Sun, and had been retooled for the web in late 1994. Netscape was the first Java licensee, so the issue became: Can we do just Java, or do we need another language?
There were people who argued strongly that Java's fine for programmers who build components, but there's a much larger audience of people who write scripts or maybe copy a script from somebody else and tweak it. These people are less specialized and may be paid to do something other than programming, like administer a network, and they write scripts part-time or on the side. If they're writing small pieces of code, they just want to get their code done with the minimal amount of fuss. Finally, we agreed that this new language should look like Java, but be a scripting language.
Like all languages, it borrowed from others. LiveScript was the official name it was given when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but we rechristened it JavaScript in a joint announcement with Sun on December 4, 1995.
JavaScript attracted a lot of developer attention, because what people wanted back then (and still want) is the ability to go one step beyond HTML and add a little bit of code that makes a web page dynamic - that makes things move, respond to user input, or change color; that makes new windows pop up; or that raises a dialog box to ask a question, with an answer necessary to proceed - things that HTML cannot express. That's really where you need a programming language, but something simpler than Java or C++.
Content creation should not be recondite. It should not be this bizarre arcana that only experts and gold-plated computer science gurus can do. There are economic advantages to lowering the entry costs in creating web content and in sharing it or aggregating it, like Netscape is doing in Web Building.
Calling JavaScript "the glue that holds web pages together" is short and easy to use, but doesn't do justice to what's going on. Glue sets and hardens, but JavaScript is more dynamic than glue. It can create a reaction and make things keep going, like a catalyst.
Paradoxically Microsoft did a lot to promote JavaScript (under the name Jscript). Now Jscript can be used as Windows scripting language but because Microsoft simultaneous promote its VBScript it never got a critical mass. Javascript can also be used in Microsoft ASP instead of VBscript.
Nevertheless Microsoft OSes are unique in the fact that they permit to use single scripting language for both command line, ASP and HTML scripting.
The Microsoft Windows Scripting Host (WSH) is a tool that allows you to run scripts written in JavaScript making Windows more Unix-like OS with a powerfull shell. Or more correctly more like OS/2 that used REXX both as a shell and a macrolanguage. The later version is 5.6 and can be freely downloaded from Microsoft. See Downloads. Microsoft also provides script debugger Download details Script Debugger for Windows NT 4.0 and Later
Using JavaScript in WSH you can now write script to automate common tasks, and to create powerful macros and logon scripts. Microsoft web site (see below) contains several documents that can be downloaded and redistributed at no charge including Jscript reference.
JavaScript is also a pretty interesting macro language, but so far only Lotus Notes uses it in such a role along with its VB clone (LotusScript). Lotus Notes 5.x used JavaScript 1.3 engine licensed from Netscape. Microsoft Office tools are VBA-based. That might change in 2007 with a new version of Office. Microsoft provides free Microsoft Windows Script Control an ActiveX® control that provides developers with an easy way to make their applications scriptable. This, in turn, enables users to extend application functionality through scripts.
Newer versions of JavaScript have good exception handling capabilities. JavaScript 1.4 (which was only around in Netscape's server products) introduced try catch exception handling and throw exception throwing. JavaScript 1.5 which was introduced in IE 5.5 further added the finally clause for try catch.
JavaScript (starting form 1.3) contains the concept of a
primitive value undefined. Like in Perl it is represented at the
lowest level of language. A variable that has not been assigned a value is of
type undefined. As in Perl can use undefined to verify
if a variable does not have a value. A JavaScript method or statement also
returns undefined, if the variable that is being evaluated does not
have an assigned value. undefined is also a property of the global object, whose value is
undefined primitive value.
Note that under ECMA-262, undefined is only defined as a primitive
value and not a property of the global object. In the code below,
since the variable input is not defined, the if
statement is evaluated to true.
var input; if(input == undefined){ document.write("input is not defined."); }
See What New in JavaScript 1.3. There are a few key concepts to remember when using JavaScript.
See also JavaScript 1.5. New features include:
Number.prototype.toFixed and Number.prototype.toExponential)const keyword.The most prominent derivative of JavaScript seems to be ActionScript. by Macromedia. Ever since the release of Flash 5.0, designers have been falling all over themselves to learn JavaScript. This bold move essentially revived the language that was on decline after Netscape demise. See actionscript_tutorial.zip (1.7MB) for details.
Dr. Nikolai Bezroukov
|
NEW! Building JavaScript applications with JSEclipse
Using JSEclipse, JavaScript programmers now have their own Eclipse plug-in that provides many important features to aid in the development of JavaScript applications. JSEclipse gives JavaScript developers the same ease of use that Eclipse has been providing in the Java language and others for years. Learn to use this tool, while creating a colony of evolving "creatures" on your page.
FREE! Go There Now!
A JavaScript object has properties associated with it. You access the properties of an object with a simple notation:
objectName.propertyNameBoth the object name and property name are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named myCar (we'll discuss how to create objects later-for now, just assume the object already exists). You can give it properties named make, model, and year as follows:
myCar.make = "Ford" myCar.model = "Mustang" myCar.year = 69;An array is an ordered set of values associated with a single variable name. Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure. So, for example, you could access the properties of the myCar object described above as follows:
myCar["make"] = "Ford" myCar["model"] = "Mustang" myCar["year"] = 67;Equivalently, each of these elements can be accessed by its index, as follows:
myCar[0] = "Ford" myCar[1] = "Mustang" myCar[2] = 67;This type of an array is known as an associative array, because each index element is also associated with a string value. To illustrate how this works, the following function displays the properties of the object, when you pass the object and the object's name as arguments to the function:
function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i + " = " + obj[i] + "\n" return result; }So, the function call show_props(myCar, "myCar") would return the following:
myCar.make = Ford myCar.model = Mustang myCar.year = 67Functions and Methods
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statments that performs a specific task.
A function definition consists of the function keyword, followed by
- the name of the function
- a list of parameters to the function, enclosed in parentheses, and separated by commas
- the JavaScript statements that define the function, enclosed in curly braces, {...}
In a Navigator application, you can use any functions defined in the current page. It is generally a good idea to define all your functions in the
HEADof a page. When a user loads the page, the functions will then be loaded first.The statements in a function can include other function calls defined for the current application.
For example, here is the definition of a simple function named pretty_print:
function pretty_print(string) { document.write("
" + string) }
This function takes a string as its argument, adds some HTML tags to it using the concatenation operator (+), then displays the result to the current document.
Defining a function does not execute it. You have to call the function for it to do its work. For example, you could call the pretty_print function as follows:
The parameters of a function are not limited to just strings and numbers. You can pass whole objects to a function, too. The show_props function from the previous section is an example of a function that takes an object as an argument.
A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
function factorial(n) { if ((n == 0) || (n == 1)) return 1 else { result = (n * factorial(n-1) ) return result } }You could call this function with an argument of one through five inside a loop as follows:
for (x = 0; x < 5; x++) { document.write(x, " factorial is ", factorial(x)) document.write(" ") }The results would be:
0 factorial is 1
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120Methods
A method is a function associated with an object. You define a method in the same way as you define a standard function. Then, use the following syntax to associate the function with an existing object:
object.methodname = function_namewhere object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.You can then call the method in the context of the object as follows:
object.methodname(params);Using this for Object References
JavaScript has a special keyword, this, that you can use to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object, and the high and low values:
function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) alert("Invalid Value!") }Then, you could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:
In general, in a method this refers to the calling object.
Creating New Objects
Both client and server JavaScript have a number of predefined objects. In addition, you can create your own objects. Creating your own object requires two steps:
- Define the object type by writing a function.
- Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name, and its properties and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, year, and color. To do this, you would write the following function:
function car(make, model, year) { this.make = make; this.model = model; this.year = year; }Notice the use of this to assign values to the object's properties based on the values passed to the function.
Now you can create an object called mycar as follows:
mycar = new car("Eagle", "Talon TSi", 1993);This statement creates mycar and assigns it the specified values for its properties. Then the value of
mycar.makeis the string "Eagle",mycar.yearis the integer 1993, and so on.You can create any number of car objects by calls to new. For example,
kenscar = new car("Nissan", "300ZX", 1992)An object can have a property that is itself another object. For example, suppose I define an object called person as follows:
function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; }And then instantiate two new person objects as follows:
rand = new person("Rand McNally", 33, "M") ken = new person("Ken Jones", 39, "M")Then we can rewrite the definition of car to include an owner property that takes a person object, as follows:
function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; }To instantiate the new objects, you then use the following:
car1 = new car("Eagle", "Talon TSi", 1993, rand); car2 = new car("Nissan", "300ZX", 1992, ken)Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:
car2.owner.nameNote that you can always add a property to a previously defined object. For example, the statement:
car1.color = "black"adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.Defining Methods
You can define methods for an object type by including a method defnition in the object type definition. For example, suppose you have a set of image GIF files, and you want to define a method that displays the information for the cars, along with the corresponding image. You could define a function such as:
function displayCar() { var result = "A Beautiful " + this.year + " " + this.make + " " + this.model; pretty_print(result) }where pretty_print is the previously defined function to display a string. Notice the use of this to refer to the object to which the method belongs.You can make this function a method of car by adding the statement
this.displayCar = displayCar;to the object definition. So, the full definition of car would now look like:function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; this.displayCar = displayCar; }
This is continuation of my earlier post on the same topic.
- objects have prototypes
This is just to remind that objects have a prototype object. JavaScript is prototype-delegation based language. If a property or method is not found in an object, it's prototype is searched. So, when you access
obj.x, the property "x" may actually be in the prototype of object "obj" (or prototype of prototype and so on). An object's prototype is accessible by a special property of the name__proto__. Note that this is non-standard Rhino specific extension. Rhino allows you to change prototype by assigning to __proto__ property!- scopes are objects
One more similarity to Lisp! In Lisp, scopes are known as "environments". Scopes are nothing but a map of variable names to variable values. In JavaScript, scopes are objects whose property names are variable names. For example,
Scopes are organized in a parent-child chain. The local scope of a function has the global scope as it's parent. Local variable scope of a nested function has enclosing function's local scope as it's parent and so on. Scope objects are also referred as "variable objects" (i.e., object that keeps variables). The "next" link in this chain is accessible by the special property called __parent__. Note that this is non-standard Rhino specific extension. Rhino allows you to change parent by assigning to __parent__ property! In addition to functions and local functions, with statements also add an innermost scope to scope-chains.thiskeyword in global/toplevel scope refers to the global object. You can walk all global variables by this function:
function printGlobals() {
for (var i in this) {
println(i + ' = ' + this[i]);
}
}How can we get hold of the "local scope" object of a function? Note that a nested function's parent scope is the local scope of the enclosing function. So, we can introduce an anonymous local function (with no code) to get it's __parent__.
With this knowledge we can write generic code to print all local variables of a function:function f() { var x = 10; // introduce an anonymous nested function just to get // it's parent scope -- which is nothing but scope of // this function. var localScope = (function() {}).__parent__; println(x); // prints 10 println(localScope.x); // prints 10 again! }var printLocals = "{ var _locals = (function(){}).__parent__; " + " for (var _i in _locals) { " + " if (/_locals/(_i) || /_i/(_i)) continue; " + " println(_i + '=' + _locals[_i].toSource()); " + " } " + "}"; function h() { var x = 32; var y = { x : 3 }; // prints all locals (x, y in this function) eval(printLocals); }Note that I've used
eval- I cannot define printLocals as a function -- because to access local scope object of given function (like h() above), I've to define an anonymous function inside the same function! So, I'm eval'ing a string to get hold of the same. But, printLocals is generic -- in the sense that you can eval it any of your function to print all locals of it. Note that although JavaScript is similar to Lisp, macros are not supported. I had to useevalto simulate macro expansion.If you combine the fact that scopes are objects and objects have prototypes, we have the following lookup rule for variables:
So, each variable lookup is potentially a 2-dimensional search!
- get the innermost scope object
- look for property with the same name as that of the variable
- if not found - chase the prototype chain (till null __proto__ is found) and look for it
- if not found, then get parent scope and look for property there. (till null __parent__ is found)
- Handling Java Exceptions
JavaScript exception handling involves try..catch statement. But, exceptions typically are JavaScript Error object or subtypes of it (but other types like string can also be thrown!). If you are getting a Java exception, that is also wrapped as a JavaScript Error object. Sometimes, you may want to get the exact Java exception thrown -- may be the Java method you called throws multiple exceptions and you may want to handle those differently. Rhino adds
javaExceptionproperty to Error objects -- this property is initialized if an Error object wraps around a Java exception.try { var obj = new java.lang.Object(); obj.wait(); } catch (e) { var exp = e.javaException; if (exp instanceof java.lang.IllegalMonitorStateException) { exp.printStackTrace(); } else if (exp instanceof java.lang.InterruptedException) { // do something differently.. } else { // something else! } }- printStackTrace
In Java debugging, we often use Throwable.printStackTrace() or Thread.dumpStack() to print stack trace. How about similar stack trace for JavaScript? It turns out that Rhino does support stack trace - with script file name, function name and line number!. Rhino adds
rhinoExceptionproperty toErrorobject. The printStackTrace method on thisrhinoExceptioninclude script functions, line numbers etc.File: test.jsThe above code prints something like:function f() { g(); } function g() { try { var c = undefined; c.toString(); } catch (e) { e.rhinoException.printStackTrace(); } } f();Note that the red lines above include script function, file name and line number. With this you can write a generic printStackTrace function asD:\>jrunscript test.ps sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot call method "toString" of undefined (p.ps#19) at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3234) at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3224) at sun.org.mozilla.javascript.internal.ScriptRuntime.typeError(ScriptRuntime.java:3240) at sun.org.mozilla.javascript.internal.ScriptRuntime.typeError2(ScriptRuntime.java:3259) at sun.org.mozilla.javascript.internal.ScriptRuntime.undefCallError(ScriptRuntime.java:3278) at sun.org.mozilla.javascript.internal.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.java:1968) at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:2931) at script.g(test.ps:19) at script.f(test.ps:2) at script(test.ps:27) at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:2250) at sun.org.mozilla.javascript.internal.InterpretedFunction.call(InterpretedFunction.java:149) at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(ContextFactory.java:337) at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(ScriptRuntime.java:2757) at sun.org.mozilla.javascript.internal.InterpretedFunction.exec(InterpretedFunction.java:160) at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1163) at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:106) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:230) at com.sun.tools.script.shell.Main.evaluateReader(Main.java:314) at com.sun.tools.script.shell.Main.evaluateStream(Main.java:350) at com.sun.tools.script.shell.Main.processSource(Main.java:267) at com.sun.tools.script.shell.Main.access$100(Main.java:19) at com.sun.tools.script.shell.Main$2.run(Main.java:182) at com.sun.tools.script.shell.Main.main(Main.java:30)function printStackTrace(exp) { if (exp == undefined) { try { exp.toString(); } catch (e) { exp = e; } } // note that user could have caught some other // "exception"- may be even a string or number - // and passed the same as argument. Also, check for // rhinoException property before using it if (exp instanceof Error && exp.rhinoException != undefined) { exp.rhinoException.printStackTrace(); } }You can call above function whereever you want script stack trace - much like
java.lang.Thread.dumpStack()call. You can get fancier output by getting the stack trace into a string and then filtering it to print only the lines that begin with at script -- so that you can view only the script frames in the trace. That is left an exercise to the reader[hint: use printStackTrace that accepts java.io.PrintWriter]
A. Sundararajan's Weblog JavaScript debugging tips (for Mustang context)
Mustang (Java SE 6) is co-bundled with Mozilla Rhino based JavaScript engine as an example implementation for javax.script API.
There are 3 use cases within JDK
- jrunscript - command line script shell
- jconsole script shell plugin
- jhat uses JavaScript engine to implement OQL (SQL-like query language) for heap queries.
There is already an experimental web application environment that uses JavaScript - http://phobos.dev.java.net.
So, we may expect that JavaScript will be employed within the JDK context more often. How about debugging support for JavaScript engine in JDK context? For Firefox, there are atleast two debuggers (that I know of!):
Rhino comes with it's own debugger -- but in Mustang, Rhino's tools are not included. Also, javax.script API does not include debugger API (yet?). For Rhino in Mustang, we have to resort to other ways to debug scripts including good old println/printf style. Few debugging tips and tricks are here...
- Use jrunscript in interactive mode for debugging.
You can use load function to load your script files (or URLs). In the interactive mode, you can call specific script functions or evaluate various expressions.
- print or alert debugging!
Use good old printf/System.out.println/alert/echo style debugging! In Mustang Java, there are built-in print and println functions always defined. If you have scripts that use alert, you can consider defining something like this:
Note that 'print' and 'println' functions print the message to output writer configured in the script context (recall that "context" is a pre-defined variable initialized with the current ScriptContext object). If you configure different output writer (may be, the one that writes messages to a file or socket etc.), you can make all print/println messages to go there.// define alert to be same as println function var alert = println;
- Use Function.toSource() to view source code of various functions.
// viewing function sources in jrunscript prompt. // built-in functions are shown as "native code" // But, you can get arity (number of arguments) // of the function js> eval.toSource()js> eval.toSource() function eval() { [native code for eval, arity=1] } // for script functions toSource() shows full source js> function add(x, y) { return x + y } js> add.toSource() function add(x, y) {return x + y;} // for Java methods we get signature as part of "source" js> var v = new java.util.Date() js> v.getDay.toSource() function getDay() {/* int getDay() */} // for overloaded Java methods, toSource() shows signatures // for all overloads js> var out = java.lang.System.out js> out.println.toSource() function println() {/* void println(boolean) void println(char) void println(int) void println() void println(long) void println(java.lang.Object) void println(java.lang.String) void println(char[]) void println(double) void println(float) */}- JavaScript object fields and array elements can be walked by
like loop.for(var i in obj) { print(obj[i]); }I frequently print all fields of an object (or elements of array) this way. Note that you will get object's methods (which are function valued properties) as well. To filter these, you can use typeof operator. You can also filter properties using property name pattern/index.
- Use JavaScript's support for higher-order functions.
JavaScript functions can be passed as arguments and returned as values. Functions can be called by apply or call functions. Functions are first-class values that can be stored in variables. You can use these to implement JavaScript AOP. You can use "interceptors" to print debug trace output. For eg. function entry/exit can be printed (along with arguments, if desired). For example, the following is a variation of JavaScript AOP referred in above link..
With the above code in a debug library (say "debug.js"), the client code can write something like:var Aspects = new Object(); // calls "before" interceptor function before calling function // name specified by fname. The function is expected to be a property // of object 'obj' Aspects.addBefore = function(obj, fname, before) { var oldFunc = obj[fname]; var newFunc = function() { return oldFunc.apply(this, before(arguments, oldFunc, this)); }; // store oldFunc for restore purpose... newFunc.oldFunc = oldFunc; obj[fname] = newFunc; }; Aspects.restore = function(obj, fname) { obj[fname] = obj[fname].oldFunc; } // tracing function entry function traceEntry(args, oldFunc, thiz) { // print the name of the function print("entering " + oldFunc.name); // print arguments var str = ""; for (var i = 0; i < args.length; i++) { str += args[i] + ", "; } print("arguments " + str); // return argument array - used by oldFunc. return args; }function add(x, y) { return x + y; } // just add two arguments add(3, 4); Aspect.addBefore(this, "add", traceEntry); // call add -- prints debug output on entry add(3, 4); // restore old "add" function without debug output Aspect.restore(this, "add");- Tracking global variables: It is better to avoid globals as much as possible.
Use objects instead. It is easy to accidentally create globals in JavaScript. For example,
While it may be possible to spot "unwanted" globals by code inspection, we can do better than that. It is possible to check global variable assignments and accesses using javax.script.Bindings used for global variable storage.function f() { x = m(); // forgot 'var' before x, x is global! // rest of the code... }Theimport javax.script.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception { // create a new ScriptEngineManager ScriptEngineManager m = new ScriptEngineManager(); // get JavaScript engine instance ScriptEngine jsEngine = m.getEngineByName("javascript"); // set a "debug" bindings for global variables jsEngine.setBindings(new DebugBindings(), ScriptContext.ENGINE_SCOPE); // eval code from a java.io.Reader object. jsEngine.eval(new FileReader(args[0])); } }DebugBindingsclass could look likeWhen running the// a simple Bindings implementation that prints debug output // whenever a variable is accessed or assigned. import javax.script.*; public class DebugBindings extends SimpleBindings { @Override public Object put(String name, Object value) { Object res = super.put(name, value); System.out.println("Global assign: " + name); return res; } @Override public Object get(Object key) { Object res = super.get(key); System.out.println("Global access: " + key); return res; } }Testclass with the followingt.jsscript file,we get the following output..function h() { // global variable assign x = 32; } h();Global assign: context Global assign: print Global assign: println Global access: javax.script.filename Global assign: h Global access: h Global assign: xNote that debug output is printed for function "assignments" as well. Note that global functions are global variables with "function" value.
- Debugging JavaScript objects
Because JavaScript is dynamically typed language, we can replace an object with any other object that "looks" like the "original". i.e., the replacement objects should just support same methods, properties -- but can do anything. (If it walks like a duck and quacks like a duck, it must be a duck). You can wrap actual object with a "debuggable" object (whose methods print debug/trace output) -- so long as debug wrapper objects supports same methods, properties. Usually, it is very easy to wrap an object with another object in JavaScript. But, if your object supports properties (a.k.a fields) it becomes tricky to wrap the same - for example, you may want to wrap XMLHttpRequest that has properties. But, you can use JSAdapter and "hook" all property or method access or assignments.
What's New In WSH 5.6
Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6). Comparison table that lest features added to the new version can be found at WSH Version Information
Setting up Remote WSH
Remote WSH, which is a new technology included in WSH 5.6, provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings. The steps below perform the tasks that enable Remote WSH.
Ajax (programming) - Wikipedia, the free encyclopedia
Asynchronous JavaScript And XML, or its acronym Ajax, is a Web development technique for creating interactive web applications. The intent is to shift a great deal of interaction to the Web surfer's computer, exchanging data with the server behind the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability. The Ajax technique uses a combination of:
- XHTML (or HTML) and CSS for marking up and styling information.
- The DOM accessed with a client-side scripting language, especially ECMAScript implementations like JavaScript and JScript, to dynamically display and interact with the information presented
- The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server.
- XML is commonly used as the format for transfering data, although any format will work, including preformatted HTML, plain text, JSON and even EBML.
Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies together. In fact, derivative/composite technologies based substantially upon Ajax, such as AFLAX, are already appearing
Wise ASP - JScript Regular Expressions
One of the most overlooked features of JScript is the regular expression interpreter, which makes string pattern matching easy. Input validation is one of the most common requirements in Web site development. At design time, you don't know what exact values viewers will enter, but you do know the format they need to use. A regular expression is a way of representing a pattern you are looking for in a string.
Fabulous Adventures In Coding Are JScript strings passed by reference
Yesterday I asked "are JScript strings passed by reference (like JScript objects) or by value (like JScript numbers)?"Trick question! It doesn't matter, because you can't change a string. I mean, suppose they were passed by reference -- how would you know? You can't have two variables refer to the "same" string and then change that string. Strings in JScript are like numbers -- immutable primitive values.
Of course, "under the covers" we actually have to pass the strings somehow. Generally speaking, strings are passed by reference where possible, as it is much cheaper in both time and memory to pass a pointer to a string than to make a copy, pass the value, and then destroy the copy.
John said:
Ok, first off, my little experience with JScript tells me that they are passed by reference. But, the comment above about it "doesn't matter" is complete BS. It matters quite a bit. Say you have an array of objects, and you want to fill the objects with data from a database. Say they contain mostly strings. Try this. Query your database, get a recordset, and set the strings in the object, to those returned by the record set. When you get done, all your objects will have null strings. Why? Because the strings were passed by reference, and the moveNext method on a record set does change the string values!Eric Lippert said:
I suspect that you're confusing two different usages of the term "by reference". When I asked whether JScript strings were passed by reference, I meant whether the STRING ITSELF was passed by ref or by value. You're talking about whether the MEMORY ADDRESS that holds the string is passed by value or by reference, which is a subtly different thing.
JScript passes objects by reference and numbers by value, but doesn't support passing references to variables at all.
Confused? It's a confusing topic. I wrote an article about the difference here:
http://blogs.msdn.com/ericlippert/archive/2003/09/15/53005.aspxECMAScript for XML (E4X) is a powerful technology for creating and processing XML content within JavaScript. We're going to continue to improve our E4X support, including adding transparent integration with the existing DOM, but developers who are building XML-based web applications can benefit from E4X support in Firefox 1.5.
You can still use the standard MIME type when using E4X:
<script type="text/javascript">However, E4X syntax may conflict with the common practice of putting scripts into HTML comments (
<!--...-->) to hide them from old browsers. E4X may also conflict with the more modern practice of putting scripts within XML CDATA sections (<[CDATA[...]]>) to allow the symbols "<" and ">" in the script (note that this does not apply to HTML). If you see inexplicable syntax errors, add "; e4x=1" to the MIME type:<script type="text/javascript; e4x=1">Note that scripts in extensions always treat HTML comments as E4X literals. That is, the "e4x=1" is implicit.
Array extras
There are seven new
Arraymethods that can be separated into two categories, item location methods and iterative methods. The item location methods are:
indexOf()- returns the index of the given item's first occurrence.
lastIndexOf()- returns the index of the given item's last occurrence.The iterative methods are:
every()- runs a function on every item in the array and returns true if the function returns true for every item.
filter()- runs a function on every item in the array and returns an array of all items for which the function returns true.
forEach()- runs a function on every item in the array.
map()- runs a function on every item in the array and returns the results in an array.
some()- runs a function on every item in the array and returns true if the function returns true for any one item.For more information, see Nicholas C. Zakas' article, Mozilla's New Array Methods.
Array and String generics
Sometimes you would like to apply array methods to strings, these treat a string as an array of characters. E.g. in order to check that every character in the variable str is a letter, you would write:
function isLetter(character) { return (character >= "a" && character <= "z"); } if (Array.prototype.every.call(str, isLetter)) alert("The string '" + str + "' contains only letters!");This notation is rather wasteful and JavaScript 1.6 introduces a generic shorthand:
if (Array.every(str, isLetter)) alert("The string '" + str + "' contains only letters!");Similarly you can easily apply String methods to any object:
var num = 15; alert(String.replace(num, /5/, '2'));developerWorks Linux Open source projects Web architecture SashXB lends mini-RAD to Linux
SashXB extends JavaScript with objects that wrap native functionality -- and provides all the necessary tools for writing applications from scratch. In this article, the developers of SashXB explore its inner workings and demonstrate how SashXB simplifies the development, download, and installation of applications.
While SashXB is not appropriate for all software projects, it is perfect for small- to medium-sized network client applications. Targeted at Web developers with HTML and JavaScript skills who want to write full-featured native applications, as well as experienced programmers who'd appreciate the convenience of rapid application development, SashXB is an open source application environment that exposes native functionality to JavaScript. It speeds the development process by encapsulating system calls, existing libraries, and other code in easily accessible "extensions," which are accessible as JavaScript objects. Low-level details are hidden from application developers, who only need to learn APIs for the new objects.
After briefly sketching out the SashXB architecture and detailing some of its important components, we will look at several applications and step through some sample code.
SashXB architecture
At its heart, SashXB consists of a runtime, locations, and extensions -- all of which are XPCOM components. Similar to Microsoft COM for Windows, XPCOM is a component system developed and used extensively by the Mozilla team that allows you to construct reusable modules. Unlike MS COM, XPCOM is cross-platform. Interfaces are defined by IDL files and can be implemented in and accessed from any language with proper bindings, which currently include C++, Python, Perl, and the Java language. All of our objects are implemented in C++.Currently SashXB supports a wide variety of extensions. Core and Linux are always installed by default.
- Core: Consists of six sub-parts:
- Channels: communicate with other Web applications
- Cursor: manipulate the cursor
- Process: start and kill processes
- UI: show basic UI input boxes
- Net: open HTTP connections (wraps Mozilla's HTTP transfer objects)
- Platform: find information about the system you're running on
- Linux: show Linux-specific UI input boxes
- Registry: store and retrieve values
- Filesystem: manage files and folders
- GTK: manipulate GUI elements (wraps GTK)
- Glade: use Glade GUIs (wraps Glade)
- Comm: use network sockets
- FTP: access remote files
- Jabber: send instant messages (wraps Jabberoo)
- XML: parse XML documents (wraps Gdome)
- Vorbis: play Ogg Vorbis sound files (wraps Ogg Vorbis)
- LDAP: access LDAP databases (wraps OpenLDAP)
- MySQL: access MySQL databases (wraps MySQL)
Hierarchical Menus with the Underrated style.display Object
You can better manage your Web real estate using hierarchical menus. Learn how with these JavaScript examples by Bill Pena, coauthor of Designing with JavaScript, 2nd Edition.
You can embed JavaScript-script engine in your C applications By David Wall
You may have been pleased to welcome Microsoft's release of the Windows Script Engine (WSE), which was initially part of the Windows NT 4.0 Option Pack and has been available for use on business operating systems since then. The WSE opens certain aspects of Windows to manipulation via the JScript scripting language, which is very much like JavaScript in many ways. The company added a bunch of objects to represent Windows features, as well.
This was cool, but the greater significance (in my humble opinion) is that Microsoft had made a move toward making JavaScript-like languages the norm for application scripting. Rather than have a whole sheaf of application-specific languages, the move promised to make it easier for us to capitalize on our knowledge of JavaScript for all kinds of fun work.
Netscape saw this as good news as well, and has released the JavaScript API as a C library that may be incorporated, via a header file, in any C application you're writing. In other words, they've put out a file -- a DLL on Windows and a shared library for Unix -- that you can compile into your C applications. You can therefore send whole scripts to the JavaScript engine for processing (it, in effect, instantiates a JavaScript parser instance like the one that's running when your browser is operating). The engine supports scripts that are in compliance with ECMA-262, and with Netscape's JavaScript 1.4 specification.
Best of all, Netscape's C Engine for JavaScript requires no licensing fee. Consider it if you need a user-scriptable application.
Netscape's introductory document on the JavaScript C Engine: http://itw.itworld.com/GoNow/a14724a53277a75978418a3
Flash ActionScript -- An Introduction
When Macromedia released version 5 of Flash, one of the major changes was to their scripting language called ActionScript. Version 5 of ActionScript adopts the syntax and many of the built-in objects of JavaScript. Indeed, the developers used the ECMA standards for ECMAScript as their model for the upgrade. This article introduces some of the features of ActionScript and Flash, and describes the differences, advantages, and disadvantages of using Flash over competing technologies.
The Language
The syntax and basic language of ActionScript is largely identical to that of JavaScript. Some noticeable and specific differences include:
- Different document object models -- Because Flash works inside of it's own environment and is concerned with the elements like movies and sounds, it has a completely different object model. You won't find built-in objects like document and window.
- Not all JavaScript statements are supported -- There are a handful of statements that are not supported in ActionScript, including the switch statement and exception handling (try/catch/throw).
- ActionScript specific statements -- The language supports some non-JavaScript statements such as event handlers (e.g., onClipEvent) and message sending (e.g., tellTarget).
- Eval function -- The Eval function, in ActionScript, only evaluates variable references
- Built-in Objects -- ActionScript supports a subset of the built-in JavaScript objects such as Date and String and a subset of their methods and properties. For example, the String object lacks the standard regular expression functions such as search and replace.
Despite these differences, experienced JavaScript programmers will be comfortable with the language. Here is a code snippet from one of the example files:
function AddDigit(digit)
{
// Add a digit to the display
if (clear)
{
clear = false;
decimal = false;
display = "0";
}
if (display == "0" && digit != ".")
{
display = digit;
}
else
{
display = display + digit;
}
}The larger learning challenge is understanding the overall environment and working with the new objects and capabilities provided.
Flash ActionScript Course Outline
Details of the Document Object Model (DOM)
... reverse order of class-based languages ... JavaScript relates Manager to Employee as its ... JavaScript
terms inheritance would be ... containment in C++ and Java ...
www.prairienet.org/~sjmccaug/dom.htm - 47k - Cached - Similar pagesServer-Side JavaScript Guide
... Server-Side JavaScript ... members in C++, to be ... subclass of Employee that adds ... of the Manager
class would have ... JavaScript implements inheritance by allowing ...
docs.iplanet.com/docs/manuals/js/server/jsguide/obj2.htm - 56k - Cached - Similar pagesWebsite Abstraction General JavaScript Tutorials
Mar 18, 2000 FAQTS - Knowledge Base - View Entry - Is there an exception-error handling mechanism in core JavaScript by Martin Honnen, Thor Larholm
Netscape's JavaScript till version 1.3 (which is the version around in NN4 since NN4.06) has no error/exception handling mechanism in the core language. JavaScript 1.4 (which is only around in Netscape's server products) introduced try catch exception handling and throw exception throwing, JavaScript 1.5 which is (will be) around in NN6 further added the finally clause for try catch. JScript 5 also supports try catch finally and throw though the exception/error object differs between JavaScript and JScript (at least at the time of writing this, it is however expected that the final releases of JavaScript 1.5 and JScript 5.5 will be ECMA compliant). Current inspection code of the form try { f(); } catch (e) { var r = ''; for (var p in e) r += p + ': ' + e[p] + '\n'; alert(r); } shows number: -2146823281 description: object expected with JScript 5 in IE and shows message: f is not defined name: ReferenceError with JavaScript 1.5 in NN6. As the ECMAScript edition 3 standard prescribes message and name properties for Error objects it seems that Netscape's JavaScript is already compliant with the standard in this regard while JScript has to catch up. So how can we use that in client side JavaScript today? That is not easy at least in a cross browser way. For Netscape you can safely use JavaScript1.4/1.5 SCRIPT blocks e.g. <SCRIPT LANGUAGE="JavaScript1.4"> try { ... } catch (e) { ... } </SCRIPT> and <SCRIPT LANGUAGE="JavaScript1.5"> try { ... } catch (e) { ... } </SCRIPT> which NN6 will execute correctly while NN4 and earlier ignore these. Unfortunately IE4/5 even with a JScript 5 scripting engine (which supports the try/catch statement) ignores JavaScript1.4/1.5 SCRIPT blocks. There seems to be no way to version a SCRIPT block for IE/JScript so that try/catch is executed in those browsers which support it and ignored otherwise. However, in an IE 4/5 only environment, such as when client data is seperated serverside for different browsers, you can use if (window.screenTop){ try { ... } cath(e) { ... } } else { ... }
[May 24, 2000] BW: Netscape and ActiveState to Co-Develop JavaScript IDE; Mozilla to Support Perl and Python
"Komodo will provide JavaScript developers with a robust, fully-featured development environment, and adding Perl and Python support to Mozilla will add new power to the Mozilla development platform."
[Jan 28, 2000] DDJ EXTENDING JSCRIPT by Paul Butcher (content of the paper is available from DDJ CD only)
Paul extends Microsoft's JScript scripting engine by adding support for constructors and arrays. In the process, he presents JScriptTest, a program that displays a UI that lets you type and execute JScript source. Additional resources include jstest.txt (listings) and jstest.zip (source code).
[Jan 28, 2000] SCRIPTS FOR WINDOWS SCRIPTING HOST by John Goalby (content of the paper is available from DDJ CD only)
Microsoft's Windows Scripting Host (WSH) is a language-independent batch-processing language for Win32. John presents a number of self-contained scripts that are useful to software developers, not just systems administrators. Additional resources include wsh.txt (listings) and wsh.zip (source code).
[Jan 21, 2000] OLE Automation in JavaScript -- Imagine being able to access and control Window's applications (like Word, etc.) using JScript! The Doc shows you how. By Dr. Yehuda Shiran.
[June 7, 1999] Win32 Scripting..... Automate!
[June 7, 1999] Winscripter
[June 7, 1999] PC Magazine PC Tech (File Management via Windows Scripting) Page 1 of 6
Recommended Links
**** Google Web Directory - Computers Programming Languages JavaScript
Microsoft Scripting Technologies Official page for Microsoft JScript
- JScript User's Guide Provides information about how to use JScript and includes a guide to regular expressions.
- JScript Language Reference Explains the elements that comprise the JScript language.
**** JavaScript Source Free JavaScripts, Tutorials, Example Code, Reference, Resources, And Help
**** Cetus Links - JavaScript - ECMAScript See also Cetus Links JScript
ABOUT.COM/Javascript tutorials, scripts, answers, and much more Javascript
JavaScript Articles, Links, and Resources - WebDeveloper.com
- HotSyte- The JavaScript Resource
- Dev Edge Online
- Doc JavaScript
- JavaScript.com
- JavaScripts.com
- The JavaScript Source
- Uncanny Programming
JavaScript.com - The Definitive JavaScript Resource JavaScript Tutorials and Free Java Scripts
Yahoo! JavaScript -- excellent resource
WebCoder.com - Your home for JavaScript and Dynamic HTML on the Web.
http://developer.netscape.com/docs/manuals/javascript.html -- old site of now defunct Netscape corporation
- Website Abstraction
- WebCoder.com - Your home for JavaScript and Dynamic HTML on the Web.
- Rolling Scrolling Status Surfers
- Roller- A JavaScript Coder
- Textual Abuse Page
- Danny Goodman's Javascript Pages
- The Javascript Planet
Tutorials
- Website Abstraction General JavaScript Tutorials -- links to tutorials
- JScript tutorial - part 1 Covers Jscript 5.5
- JScript reference
- Website Abstraction General JavaScript Tutorials
- JScript Tutorial
- Voodoo's Intro to JavaScript (see also Voodoo's Intro to JavaScript)
- Core JavaScript 1.4 Guide
- Client-Side JavaScript 1.3 Guide
- Excerpts from the JavaScriptTM Bible (3rd Edition)
- Webmonkey JavaScript Index
- JavaScript Tutorial for Programmers
- Beginners Guide to JavaScript
- Experiments in JavaScript
- JavaScript Tutorial ( http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html )
- Web Resources Tutorials The Primers Let's Learn JavaScript!
Quiz:
Older e-books
- Que: SE USING JSCRIPT
- Author: Mark Reynolds
Price: $49.99 US
Publisher: Que
ISBN: 078971079X
Publication Date: 12/5/96
Pages: 700- Que: SE Using JavaScript
Articles
Introduction to Regular Expressions Microsoft guide to Jscript regular expressions
The information contained in these pages is intended to provide a introduction to regular expressions in general.
While an attempt has been made to make each topic stand on it's own, much of the information contained in these topics relies upon the understanding of a previously introduced feature or concept. Therefore, it's recommended that you peruse these topics sequentially for the best overall understanding of the material.
The Introduction to Regular Expressions consists of the following individuals topics:
- Regular Expressions
- Early Beginnings
- Uses for Regular Expressions
- Regular Expression Syntax
- Build a Regular Expression
- Order of Precedence
- Ordinary Characters
- Special Characters
- Non-Printable Characters
- Character Matching
- Quantifiers
- Anchors
- Alternation and Grouping
- Backreferences
Windows and Frame from JavaScript The Definitive Guide, 3rd Edition
JavaScript Guidelines and Best Practice
NavWorks- Javascript Introduction
JavaScript Objects and Operators
FAQs
Reference
- Microsoft Windows Script 5.6 Documentation
This download provides extensive reference and conceptual documentation for all of Microsoft Windows Script Technologies.
ECMA-262 JavaScript Language Specification
- Viewable, downloadable, and printable as a PDF file ECMA-262.pdf
- Microsoft Word self-extracting binary
Netscape (Documentation JavaScript)
JavaScript FAQ by Alexei Kourbatov
Microsoft Word self-extracting binary of Javascript standart
A free copy of the JavaScript Object Roadmap and Quick Reference. The final version from the book is now available here (cover date: 2 January 1998). It is a .pdf (Adobe Acrobat) file that prints out on both sides of two pieces of paper and folds into a convenient reference. The new version shows Navigator and Internet Explorer compatibility ratings for every Netscape Navigator object and its properties, methods, and event handlers. I use it all the time.
If you have the Acrobat reader plug-in, you can preview the entire document. Or download your choice of a Windows zipped version or Macintosh binhex version. The download versions include step-by-step instructions for printing, assembling, and folding the pages into a handy pamphlet format.
Script collections
- Microsoft Script Repository
- Microsoft Misc. Code Samples
- The JM Web JavaScript collection
- d e v h e a d Resources ScriptLibrary
- The JavaScript Planet - Collection with 371 FREE examples!
JScript
**** Cetus Links JScript
Visual Javascript
No longer supported. See Netscape Visual Javascript 1.0 End Of Life Statement.
Papers
- Lab Note Building Distributed Web Applications with Visual JavaScript (Web Techniques, Feb 1998)
- Using components to develop applications, an introduction to Visual JavaScript
- Levelling the Playing Field: Visual JavaScript
Books
- new:Server Scripts With Visual Javascript (Hands-On Web Development)
- Netscape Visual JavaScript for Dummies (Amazon Link)
- Official Netscape Visual JavaScript Book (Amazon Link)
- Server Scripts With Visual JavaScript (Hands-On Web Development) (Amazon Link)
- Teach Yourself Visual JavaScript in 21 Days, Professional Reference Edition (Amazon Link)
Copyright © 1996-2007 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Standard disclaimer: The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.
Debugging Articles
- Debugging JavaScript programs - JavaWorld July 1996
- CNET Builder.com - Web Programming - Readers Write Debugging JavaScript Debugging JavaScript - 9-14-99
- The JavaScript Source Debugging Guide
- JavaScript - Debugging
- JavaScript Debugging
- Laura Lemay's Web Workshop--JavaScript
- webreview.com - Debugging JavaScript
- JavaScript Debugging -- Overview of Debugging in Netscape 6. Referenced Documents:
- NEW 'query-part' patch for Netscape JavaScript Debugger 1.1
- Documents for JavaScript Debugger for NGT
- Basic JSD architecture
- An old proposal for a JavaScript Debugger in JavaScript for Mozilla
- An old high-level laundry list of things that ought to be done
- js/jsd/README
- js/jsdj/README
- js/jsdj/build/README
- js/jsdj/classes/com/netscape/jsdebugging/ifcui/README
- Advanced JavaScript Debugging Technique By Danny Goodman -- nothing advanced but still might be useful
- Debugging JavaScript programs - JavaWorld July 1996 -- decent . Republished in The JavaScript Source: Debugging Guide
- JavaScript Programming: Debugging / WebDeveloper.com by Heidi Brumbaugh
- CNET Builder.com - Web Programming - Readers Write: Debugging
- JavaScript - Debugging -- weak
- JavaScript Debugging -- slides
Jscript Debugger
Microsoft Script Debugger is a debugging environment that extends any Microsoft ActiveX Scripting host application (for example, Internet Explorer or Internet Information Server).
- Run your server-side scripts one line at a time.
- Open a command window to monitor the value of variables, properties, or array elements, during the execution of your server-side scripts.
- Set pauses to suspend execution of your server-side scripts (using either the debugger or a script command) at a particular line of script.
- Trace procedures while running your server-side script.
- To add breakpoints to your scripts insert a debugger statement before a suspect line of script. For example, the following script includes a debugger