Border Crossing: javascript Language Features

Source: Internet
Author: User
Tags javascript extension
Http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html? S_tact = 105agx52 & s_cmp = techcsdn

People think that Programming Language A member of minor importance. The formation of such ideas can be attributed to its development tools, complex and inconsistent HTML page-oriented document object models, and inconsistent browser implementations. But Javascript is definitely not as simple as a toy. In this article, Bruce Tate introduces you to the language features of JavaScript.

Almost every web developer has had the experience of cursing JavaScript. This controversial language is affected by its complicated programming model called the Document Object Model (DOM), poor implementation and debugging tools, and inconsistent browser implementations. Until recently, many developers thought that JavaScript was an inevitable disaster in the best aspect, but in the worst aspect, it was just a toy.

However, JavaScript is becoming increasingly important and has become a widely used scripting language for web development. The recovery of JavaScript forces some industry leaders to review the programming language. Programming technologies such as Ajax (Asynchronous JavaScript + XML) make web pages more attractive. The complete Web development framework, such as Apache cocoon, makes JavaScript applications more and more, making it not only a simple script for making web pages. A JavaScript-based style called ActionScript also promotes the development of Macromedia's flash client framework. The implementation of rhino running on JVM makes JavaScript the preferred scripting language for Java developers (see references ).

My friend and colleague Stuart Halloway is an Ajax expert who once made such an opening remark in his JavaScript Course: "By 2011, javascript will be recognized as a kind of possession to develop modern applicationsProgramA complete set of new features required ". He then introduced that javascript programs are 10 times closer than similar Java programs, and he continued to demonstrate some of the language features that make them.

About this series

In the cross-border series, the author Bruce Tate put forward the idea that today's Java programmers will be very helpful by learning other technologies and languages. The programming field has changed. Java is no longer the best choice for all development projects. Other frameworks are influencing the way Java frameworks are built, and concepts from other linguistics also contribute to Java programming. For Python (or Ruby, smalltalk, etc)CodeMay change the Java coding method.

The Programming Concepts and technologies introduced in this series are fundamentally different from Java development, but they can be directly applied to Java programming. In some cases, these technologies need to be integrated to take advantage of them. In other cases, these concepts can be directly applied. Independent tools are not important. What's important is that other languages and frameworks can affect JavaCommunityDevelopers, frameworks, and even basic methods.

In this articleArticleIn, I will show you some JavaScript features to see how these features make it so attractive:

    • Higher-order functions:A higher-order function can take a function as a parameter or return a function. This feature allows JavaScript programmers to manipulate functions using methods not provided by Java.

    • Dynamic type:Through delayed binding, JavaScript can be more accurate and flexible.
    • Flexible object model:The object model of JavaScript uses a relatively uncommon Method for inheritance-calledPrototype-- Instead of the more common class-based object model in Java.

You may already be familiar with dynamic type models, functional programming in the form of higher-order functions, and open object models.Crossing boundariesRelated articles have been introduced in the series. If you have never performed any formal Javascript development, you may think that these features belong to very complex languages, such as Python, lisp, smalltalk, and Haskell, it is not what a language like JavaScript can provide. Therefore, I will describe these concepts using actual code examples.

Start now

You do not need to set JavaScript. If you can read this article in your browser, it will prove that you are ready. All programming examples in this article can be run in most browsers. I am using Firefox.

Used in<SCRIPT type = 'text/JavaScript '>And</SCRIPT>The javascript contained between tags loads simple web pages. Listing 1 shows the Hello, world text:

Listing 1. Hello, world

<SCRIPT type = 'text/JavaScript '> alert ('hello, world.') </SCRIPT>

To run this code, you only need to create a file named example1.html. Copy the code in Listing 1 to the file and load the file in the browser (see the download section to get all the sample HTML files used in this article ). Note that the code is executed immediately every time this page is reloaded.

AlertIt is a function call and only one string is used as the parameter. Figure 1 shows the warning box popped up by the code in Listing 1. The text "Hello, world" is displayed ". If the code is within the html body (no body is specified currently, but the browser can accept irregular HTML, and the whole page is silently processed as a body ). Once the page is loaded, JavaScript will be executed immediately.

Figure 1. Hello, world

If you want to delay the execution, you can<Head>Element declaration JavaScript function, as shown in Listing 2:

Listing 2. delayed execution

<Head> <SCRIPT type = 'text/JavaScript '> function Hello () {alert ('hello, world. ')} </SCRIPT> 

Input the code in Listing 2 to an HTML file, load the file in the browser, and clickSay helloButton, as shown in result 2:

Figure 2. delayed execution



Back to Top

High-order functions

From list 2, you can get a general understanding of some JavaScript capabilities in manipulating functions. Pass the function name to HTMLButtonTag and use the built-in HTML event model. When using JavaScript, I will often store functions in variables or arrays (in the object model section later in this article, you will see that JavaScript Object Model policies are heavily used ). For example, check listing 3:

Listing 3. Using variables to manipulate Functions

<Head> <SCRIPT type = 'text/JavaScript '> Hot = function hot () {alert ('sweat. ')} cold = function cold () {alert ('shiver. ')} function swap () {temp = hot = cold = temp alert ('swapped. ')} </SCRIPT> 

Functions are a class of objects in JavaScript and can be manipulated freely. First, I declare two functions:HotAndCold. And store them in different variables. Click the hot or cold button to call the corresponding function to generate an alarm. Next, declare another function to exchange the values of the hot and cold buttons and associate the function with the third button. The button displays the alarm shown in 3:

Figure 3. manipulation functions

This example shows that functions can be processed just like other variables. C developers can easily regard this conceptFunction pointerFunction, but JavaScript higher-order functions are more powerful. This feature allows JavaScript programmers to easily process actions or functions like other variable types.

Using a function as a function parameter or returning a function as a value belongs to the field of Higher-order functions. Listing 4 makes a slight modification to listing 3, showing the higher-order functions that can return functions:

Listing 4. High-Order Functions

<Head> <SCRIPT type = 'text/JavaScript '> Function Temperature () {Return Current} hot = function hot () {alert ('hot. ')} cold = function cold () {alert ('cold. ')} current = hot function swap () {If (current = hot) {current = cold} else {current = hot }}</SCRIPT> 

This example solves a common problem: how to attach the behavior in the change to a user interface event? Through higher-order functions, this is easy to do.TemperatureReturn of Higher-Order FunctionsCurrentAnd current can haveHotOrColdFunction. Let's take a look at some outdated function calls:Temperature ()(). The first group of parentheses is used to callTemperatureFunction. The second set of brackets is calledTemperature Return. Figure 4 shows the output:

Figure 4. High-Order Functions

Higher-order functions are the basis of functional programming. Compared with object-oriented programming, functional programming represents a higher level of abstraction. However, the strength of JavaScript is not limited to higher-order functions. Javascript dynamic types are extremely suitable for UI development.



Back to Top

Dynamic type

Through static types, the compiler can check the values of parameters and variables or the returned values allowed for a given operation. The advantage is that the compiler can perform additional error checks. In addition, static types can provide more information for tools such as IDE, and provide other features, such as better Code Completion functions. However, static types also have the following Disadvantages:

    • Intention must be declared in advance, which often results in less flexibility. For example, changing a Java class changes the type of the class and must be re-compiled. In contrast, Ruby allows open classes, but changing a Java class will change the class type.

    • To implement the same function, you must enter more code. For example, the input type information must be included in the form of parameters, the return value must be in the form of functions, and the types of all variables. In addition, all variables must be declared and the type must be converted explicitly.
    • Static language compilation-the deployment cycle is longer than that of dynamic languages, although some tools can be used to alleviate this problem to some extent.

Static types are more suitable for languages used to build middleware or operating systems. UI development often requires higher efficiency and flexibility, so it is more suitable for dynamic types. I know that this practice is dangerous. I believe that web developers who have used JavaScript have racked their brains for variables of the Error Type that should have been detected by the compiler. However, its advantages are undeniable. The following is an example.

First, consider the situation of an object. In listing 5, create a new object and access a non-existent property namedColor:

Listing 5. Introduce an attribute

<SCRIPT type = 'text/JavaScript '> balank_object = new object (); balank_object.color = 'Blue' alert ('the color is '+ balank_object.color) </SCRIPT>

When the application is loaded and executed, the following result is displayed:

Figure 5. Introduce attributes

JavaScript does not reportBlueProperty does not exist. Fans of the static type are intimidated by this example because errors in this example are well concealed. Although this practice may make you feel a little unfair, you cannot deny its great temptation. You can quickly introduce attributes. If you combine this example with the previous example, you can also introduce behavior. Remember, variables can save functions! Therefore, based on dynamic types and high-order functions, you can introduce any behavior to the class at any time.

You can easily override listing 5, as shown in Listing 6:

Listing 6. Introduction

<SCRIPT type = 'text/JavaScript '> blank_object = new object (); blank_object.color = function () {return 'blue'} alert ('the color is' + blank_object.color ()) </SCRIPT>

From the above example, we can see that different concepts of javascript can be easily transformed back and forth, and their meanings have changed a lot-for example, whether to introduce behavior or data-but the syntax changes are very small. The good scalability of this language is one of its advantages, but it is also its disadvantage. In fact, the object model of the language itself is a manifestation of the degree of JavaScript extension.



Back to Top

Object Model

So far, you should have a correct comment on JavaScript, which is not as simple as a toy. In fact, many people have used their object models to create extremely complex and well-designed object-oriented software. However, the object model, especially the object model used for inheritance, is not what you always think.

The Java language is class-based. When building an application, a new class that can be used as a template for all objects is also built. Then callNewTo instantiate the template and create a new object. In JavaScript, a prototype is created. This prototype is an instance that allows you to create all future objects.

Now, let's put down these abstract concepts to view some actual code. For example, listing 7 creates a simpleAnimal, It hasNameAttributes andSpeakAction. Other animals inherit from this base.

Listing 7. Create a constructor

<SCRIPT type = 'text/JavaScript '> animal = function () {This. Name = "nobody" This. Speak = function () {return "who am I? "} Myanimal = new animal (); alert (the animal named '+ myanimal. Name + 'says' + myanimal. Speak (); </SCRIPT>

Result 6 of listing 7 is shown:

Figure 6. Create a constructor

For Java developers, the code in listing 7 looks somewhat unfamiliar and strange. In fact, for many JavaScript developers who have not personally built objects, the Code also looks a little unfamiliar and strange. The following explanation may help you better understand the code.

In fact, you only need to focus on the three pieces of information. First, JavaScript uses nested functions to represent objects. This means thatAnimalIs a valid syntax. Second, JavaScript constructs Objects Based on prototypes or existing object instances, rather than class templates.Funct ()Is a call,New Animal ()But based onAnimalTo construct an object. Finally, in Javascript, the object is only a collection of functions and variables. Each object is not related to the type, so you can freely modify this structure.

Go back to listing 7. As you can see, JavaScript is based onAnimalThe prototype specified in defines a new object:Myanimal. You can then use the attributes and functions in the prototype, or even redefine the functions and attributes. This flexibility may make Java developers unable to stand, because they are not used to this behavior, but it is indeed a very powerful model.

Now I want to go further. You can also usePrototypeInstance variables to specify the basis of the object. The method is to setPrototypeThe instance variable points to the parent of the inheritance chain. Set this wayPrototypeThen, the object you create will inherit the attributes and functions of the unspecified objects. In this way, you can imitate the Object-oriented Inheritance concept. Take listing 8 as an example:

Listing 8. Inheritance through prototype

<SCRIPT type = 'text/JavaScript '> animal = function () {This. Name = "nobody" This. Speak = function () {return "who am I? "} Dog = function () {This. Speak = function () {return" Woof! "} Dog. prototype = new animal (); myanimal = new dog (); alert (the animal named '+ myanimal. name + 'says '+ myanimal. speak (); </SCRIPT>

In listing 8,DogPrototype. This prototype is based onAnimal.DogRedefinitionSpeak ()Method, but notName ()Method. Then, the prototypeDogSetAnimal. Figure 7 shows the result:

Figure 7. Prototype inheritance

This also shows how JavaScript solves the problem of attribute or method reference:

    • Javascript creates an instance based on the original prototype, which is defined in the constructor. Any reference to a method or attribute will use the generated original copy.

    • You can redefine these variables in an object just like any other variables. This will inevitably change this object. Therefore, any attribute or function you explicitly define has a higher priority than those defined in the original prototype.
    • If you explicitly set the namePrototypeJavascript will find any undefined instance variables or attributes in this instance. This search is recursive: IfPrototypeThe instance defined inItsSearch in the prototype, and so on.

So what is the Javascript inheritance model? It depends on how you define it. You need to define the inheritance behavior so that it can be overwritten. However, in essence, JavaScript is more like a functional language than an object-oriented language. It uses intelligent syntax and semantics to simulate highly complex behaviors. Its object model is extremely flexible, open, and powerful, and has all its reflection. Some may say it is too flexible. My advice is to select a proper tool based on the specific job needs.



Back to Top

Conclusion

The JavaScript Object model is built on other features of the language to support a large number of libraries, such as Dojo (see references ). This flexibility allows each framework to change the object model in a fine-grained manner. To some extent, this flexibility is a great disadvantage. It can lead to terrible interoperability issues (although the flexibility of the language can partially alleviate these problems ).

On the other hand, flexibility is a huge advantage. Java has been suffering from insufficient flexibility because its basic object model is not yet flexible enough to be scalable. A typical enterprise-level developer must learn many things to successfully use the Java language, and some outstanding open source code projects and new technologies are emerging, for example, Aspect-Oriented Programming, spring programming framework, and bytecode enhancement libraries bring a lot of code to be learned.

Finally, the excellent flexibility of JavaScript makes you realize the powerful functions of some advanced languages. Of course, you do not need to make such trade-offs and trade-offs for each project or most projects. But understand the advantages and disadvantages of a language-by referring to a large amount of information, it is not just based on advertising or public opinions-it gives you better control over when to use and when not to use the language. When you modify JavaScript web widgets, you at least know how to make the language take advantage of it. Continue to cross the border.

Download

Description Name Size Download Method
Sample HTML file in this article J-cb12196.zip 3kb HTTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.