西安司机招聘赶集网:JavaScript - Wikipedia

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 22:24:26
From Wikipedia, the free encyclopediaJump to: navigation,searchNot to be confused with Java (programming language).For the use of JavaScript on Wikipedia, see Wikipedia:JavaScript. JavaScript Paradigm Multi-paradigm: scripting, prototype-based, imperative, functional[1] Appeared in 1995 Designed by Brendan Eich Developer Netscape Communications Corporation, Mozilla Foundation Stable release 1.8.2[2] (June 22, 2009; 20 months ago (2009-06-22)) Preview release 1.8.5[3] (July 27, 2010; 7 months ago (2010-07-27)) Typing discipline dynamic, weak, duck Major implementations KJS, Rhino, SpiderMonkey, V8, WebKit Influenced by C, Scheme, Java, Perl, Python, Self Influenced JScript, JScript .NET, Objective-J, TIScript JavaScript at Wikibooks JavaScript Filename extension .js Internet media type application/javascript, text/javascript[4] Uniform Type Identifier com.netscape.javascript-?source[5] Type of format Scripting language This article is part of

the JavaScript series.

JavaScript JavaScript syntax JavaScript topics This box: view · talk · edit

JavaScript, also known as ECMAScript [6] is a prototype-based object-oriented[7] scripting language that is dynamic, weakly typed and has first-class functions. It is also considered a functional programming language[1] like Scheme and OCaml because it has closures and supports higher-order functions.[8]

JavaScript is an implementation of the ECMAScript language standard and is primarily used in the form of client-side JavaScript, implemented as part of a web browser in order to provide enhanced user interfaces and dynamic websites. This enables programmatic access to computational objects within a host environment.

JavaScript's use in applications outside web pages—for example in PDF-documents, site-specific browsers and desktop widgets—is also significant. Newer and faster Javascript VMs and frameworks built upon them (notably Node.js) have also increased the popularity of Javascript for server-side web apps.

JavaScript uses syntax influenced by that of C. JavaScript copies many names and naming conventions from Java,but the two languages are otherwise unrelated and have very differentsemantics. The key design principles within JavaScript are taken fromthe Self and Scheme programming languages.[9]

Contents

[hide]
  • 1 History
  • 2 Trademark
  • 3 Features
    • 3.1 Imperative and structured
    • 3.2 Dynamic
    • 3.3 Functional
    • 3.4 Prototype-based
    • 3.5 Miscellaneous
    • 3.6 Vendor-specific extensions
  • 4 Syntax and semantics
    • 4.1 Simple examples
    • 4.2 More advanced example
  • 5 Use in web pages
    • 5.1 Example - use in web pages
    • 5.2 Compatibility considerations
    • 5.3 Accessibility
    • 5.4 Security
      • 5.4.1 Cross-site vulnerabilities
      • 5.4.2 Misplaced trust in the client
      • 5.4.3 Browser and plugin coding errors
      • 5.4.4 Sandbox implementation errors
  • 6 Uses outside web pages
    • 6.1 Embedded scripting language
    • 6.2 Scripting engine
    • 6.3 Application platform
  • 7 Development tools
  • 8 Versions
  • 9 Related languages and features
    • 9.1 JavaScript and Java
  • 10 See also
  • 11 References
  • 12 Further reading
  • 13 External links

[edit] History

Anyway I know only one programming language worse than C and that is Javascript. [...] I was convinced that we needed to build-in a programming language, but the developers, Timfirst, were very much opposed. It had to remain completely declarative.Maybe, but the net result is that the programming-vacuum filled itselfwith the most horrible kluge in the history of computing: Javascript.

Robert Cailliau[10]

JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, and finally to JavaScript.[11][12]LiveScript was the official name for the language when it first shippedin beta releases of Netscape Navigator 2.0 in September 1995, but itwas renamed JavaScript in a joint announcement with Sun Microsystems onDecember 4, 1995 [13] when it was deployed in the Netscape browser version 2.0B3. [14]

The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language,and the choice has been characterized by many as a marketing ploy byNetscape to give JavaScript the cachet of what was then the hot newweb-programming language. [15] [16] It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser.[citation needed]

JavaScript very quickly gained widespread success as a client-side scripting language for web pages. As a consequence, Microsoft developed a partially compatible dialect of the language, naming it JScript to avoid trademark issues. JScript added new date methods to fix the Y2K-problematic methods in JavaScript, which were based on Java's java.util.Date class.[17] JScript was included in Internet Explorer3.0, released in August 1996. The dialects are perceived to be sosimilar that the terms "JavaScript" and "JScript" are often usedinterchangeably. Microsoft, however, notes dozens of ways in whichJScript is not ECMA-compliant.[18]

In November, 1996 Netscape announced that it had submitted JavaScript to Ecma International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript.[19]

JavaScript has become one of the most popular programming languageson the web. Initially, however, many professional programmers denigratedthe language because its target audience was web authors and other such"amateurs", among other reasons.[20] The advent of Ajaxreturned JavaScript to the spotlight and brought more professionalprogramming attention. The result was a proliferation of comprehensive frameworks and libraries,improved JavaScript programming practices, and increased usage ofJavaScript outside of web browsers, as seen by the proliferation of server-side JavaScript platforms.

In January 2009 the CommonJSproject was founded with the goal of specifying a common standardlibrary mainly for JavaScript development outside the browser.[21]

[edit] Trademark

"JavaScript" is a trademark of Oracle Corporation. It is used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.[22]

[edit] Features

The following features are common to all conforming ECMAScript implementations, unless explicitly specified otherwise.

[edit] Imperative and structured

JavaScript supports all the structured programming syntax in C (e.g., if statements, while loops, switch statements, etc.). One partial exception is scoping:C-style block-level scoping is not supported (instead, JavaScript hasfunction-level scoping). JavaScript 1.7, however, supports block-levelscoping with the let keyword. Like C, JavaScript makes a distinction between s and statements. One syntactic difference from C is automatic semicolon insertion, in which the semicolons that terminate statements can be omitted.[23]

[edit] Dynamic

dynamic typing
As in most scripting languages, types are associated with values, not with variables. For example, a variable x could be bound to a number, then later rebound to a string. JavaScript supports various ways to test the type of an object, including duck typing.[24]
object based
JavaScript is almost entirely object-based. JavaScript objects are associative arrays, augmented with prototypes (see below). Object property names are string keys: obj.x = 10 and obj["x"] = 10 are equivalent, the dot notation being syntactic sugar.Properties and their values can be added, changed, or deleted atrun-time. Most properties of an object (and those on its prototypeinheritance chain) can be enumerated using a for...in loop. JavaScript has a small number of built-in objects such as Function and Date.
run-time evaluation
JavaScript includes an eval function that can execute statements provided as strings at run-time.

[edit] Functional

first-class functions
Functions are first-class; they are objects themselves. As such, they have properties and methods, such as length and call();[25] and they can be assigned to variables, passed as arguments, returned by other functions, and manipulated like any other object.[26] Any reference to a function allows it to be invoked using the () operator.[27]
nested functions
'Inner' or 'nested' functions are functions defined within anotherfunction. They are created each time the outer function is invoked. Inaddition to that, the scopeof the outer function, including any constants, local variables andargument values, become part of the internal state of each innerfunction object, even after execution of the outer function concludes.[28]
closures
JavaScript allows nested functions to be created, with the lexical scope in force at their definition, and has a ()operator to invoke them now or later. This combination of code that canbe executed outside the scope in which it is defined, with its ownscope to use during that execution, is called a closure in computer science.[29]

[edit] Prototype-based

prototypes
JavaScript uses prototypes instead of classes for inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.
functions as object constructors
Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object for that invocation. The constructor's prototype property determines the object used for the new object's internal prototype. JavaScript's built-in constructors, such as Array, also have prototypes that can be modified.
functions as methods
Unlike many object-oriented languages, there is no distinction between a function definition and a methoddefinition. Rather, the distinction occurs during function calling; afunction can be called as a method. When a function is called as amethod of an object, the function's local this keyword is bound to that object for that invocation.

[edit] Miscellaneous

run- time environment
JavaScript typically relies on a run-time environment (e.g. in a web browser)to provide objects and methods by which scripts can interact with "theoutside world". In fact, it relies on the environment to provide theability to include/import scripts (e.g. HTML

[edit] Compatibility considerations

Main article: Web interoperability

Since JavaScript runs in widely varying environments, an important part of testing and debugging it is testing across browsers.

The DOMinterfaces for manipulating web pages are not part of the ECMAScriptstandard, or of JavaScript itself. Officially, they are defined by aseparate standardization effort by the W3C; in practice, browser implementations differ from the standards and from each other, and not all browsers execute JavaScript.

To deal with these differences, JavaScript authors can attempt towrite standards-compliant code which will also be executed correctly bymost browsers; failing that, they can write code that checks for thepresence of certain browser features and behaves differently if they arenot available.[33]In some cases, two browsers may both implement a feature but withdifferent behavior, and authors may find it practical to detect whatbrowser is running and change their script's behavior to match.[34][35] Programmers may also use libraries or toolkits which take browser differences into account.

Furthermore, scripts may not work for some users. For example, a user may:

  • use an old or rare browser with incomplete or unusual DOM support,
  • use a PDA or mobile phone browser which cannot execute JavaScript,
  • have JavaScript execution disabled as a security precaution,
  • use a speech browser due to, for example, a visual disability.

To support these users, web authors can try to create pages which degrade gracefullyon user agents (browsers) which do not support the page's JavaScript.In particular, the page should remain usable albeit without the extrafeatures that the JavaScript would have added. An alternative approachthat many find preferable is first to author content using basictechnologies that work in all browsers, then to enhance it for userswith JavaScript enabled, testing for feature support before adding theenhancements. This is known as progressive enhancement.

[edit] Accessibility

Main article: Web accessibility

Assuming that the user has not disabled its execution, client-sideweb JavaScript should be written to enhance the experiences of visitorswith visual or physical disabilities, and certainly should avoid denying information to these visitors.[36]

Screen readers, used by the blind and partially sighted,can be JavaScript-aware and so may access and read the page DOM afterthe script has altered it. The HTML should be as concise, navigable and semantically rich as possible whether the scripts have run or not. JavaScript should not be totally reliant on mouse-specific events so as to deny its benefits to users who either cannot use a mouse or who choose to favor the keyboard for whatever reason. Equally, although hyperlinks and webforms can be navigated and operated from the keyboard, accessible JavaScript should not require keyboard events either. There are device-independent events such as onfocus and onchange that are preferable in most cases.[36]

JavaScript should not be used in a way that is confusing ordisorientating to any web user. For example, using script to alter ordisable the normal functionality of the browser, such as by changing theway the back-button or the refresh event work, is usually best avoided.Equally, triggering events that the user may not be aware of reducesthe user's sense of control as do unexpected scripted changes to thepage content.[37]

Often the process of making a complex web page as accessible as possible becomes a nontrivialproblem where issues become matters of debate and opinion, and wherecompromises are necessary in the end. However, user agents and assistive technologies are constantly evolving and new guidelines and relevant information are continually being published on the web.[36]

[edit] Security

JavaScript and the DOM provide the potential for malicious authors todeliver scripts to run on a client computer via the web. Browserauthors contain this risk using two restrictions. First, scripts run in asandboxin which they can only perform web-related actions, not general-purposeprogramming tasks like creating files. Second, scripts are constrainedby the same origin policy:scripts from one web site do not have access to information such asusernames, passwords, or cookies sent to another site. MostJavaScript-related security bugs are breaches of either the same originpolicy or the sandbox.

[edit] Cross-site vulnerabilities

Main articles: Cross-site scripting and Cross-site request forgery

A common JavaScript-related security problem is cross-site scripting, or XSS, a violation of the same-origin policy.XSS vulnerabilities occur when an attacker is able to cause a targetweb site, such as an online banking website, to include a maliciousscript in the webpage presented to a victim. The script in this examplecan then access the banking application with the privileges of thevictim, potentially disclosing secret information or transferring moneywithout the victim's authorization. A solution to XSS vulnerabilities isto use HTML escaping whenever displaying untrusted data.

Some browsers include partial protection against reflected XSSattacks, in which the attacker provides a URL including maliciousscript. However, even users of those browsers are vulnerable to otherXSS attacks, such as those where the malicious code is stored in adatabase. Only correct design of Web applications on the server side canfully prevent XSS.

XSS vulnerabilities can also occur because of implementation mistakes by browser authors.[38]

Another cross-site vulnerability is cross-site request forgeryor CSRF. In CSRF, code on an attacker's site tricks the victim'sbrowser into taking actions the user didn't intend at a target site(like transferring money at a bank). It works because, if the targetsite relies only on cookies to authenticate requests, then requestsinitiated by code on the attacker's site will carry the same legitimatelogin credentials as requests initiated by the user. In general, thesolution to CSRF is to require an authentication value in a hidden formfield, and not only in the cookies, to authenticate any request thatmight have lasting effects. Checking the HTTP Referrer header can alsohelp.

"JavaScript hijacking" is a type of CSRF attack in which a