外文文献-Secrets of the JavaScript Ninja_第1页
外文文献-Secrets of the JavaScript Ninja_第2页
外文文献-Secrets of the JavaScript Ninja_第3页
外文文献-Secrets of the JavaScript Ninja_第4页
外文文献-Secrets of the JavaScript Ninja_第5页
已阅读5页,还剩14页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

大连民族学院毕业设计(论文)外文文献原文及译文学 院:计算机科学与工程学院专 业:班 级:学生姓名:指导教师: 翻译文献题目: Secrets of the JavaScript Ninja -chapter 3 Functions are fundamental出处: John Resig、Bear Bibeault / Manning Publications / 2012-11-28 / USD 39.99 此文献题目按照原书的内容从上往下的顺序逐段依次翻译原:In this chapter we discuss Why understanding functions is so crucial How functions are first-class objects How the browser invokes functions Declaring functions The secrets of how parameters are assigned The context within a function译: 在这章我们将讨论以下几点1.为什么理解函数如此重要2.函数是如何成为一级对象?3.浏览器是如何调用函数?4.声明函数5.参数是如何传递的6.函数上下文原:You might have been somewhat surprised, upon turning to this part of the bookdedicated to JavaScript fundamentals, to see that the first topic of discussion is tobe functions rather than objects.Well certainly be paying plenty of attention to objects (particularly in chapter 6),but when it comes down to brass tacks, the main difference between writing Java-Script code like the average Joe (or Jill) and writing it like a JavaScript ninja isunderstanding JavaScript as a functional language. The level of the sophistication ofall the code youll ever write in JavaScript hinges upon this realization.译: 你可能会很惊讶,当本书这章主要讲 javascript 基础时,我们第一个讨论的话题不是对象而是函数。我们将会重点讨论对象(尤其是在第六章) ,但当谈论一个实质问题:像初级程序员那样编写 javascript 代码和像高级程序员把 javascript 当初函数式语言那样编写 javascript 代码的主要区别时, javascript 中,你所写过的成熟老练的代码一下子就呈现出来了。原:If youre reading this book, youre not a rank beginner and were assuming thatyou know enough object fundamentals to get by for now (and well be taking a lookat more advanced object concepts in chapter 6), but really understanding functionsin JavaScript is the single most important weapon you can wield. So important, in fact,that this and the following two chapters are going to be devoted to thoroughly understandingfunctions in JavaScript.译:当你读这本书的时候,我们不把你当作是将入门的初学者,而是假设到现在为止你已经足够了解对象基础(我们将在第六章讲解更多高级对象概念) ,但是在 javascript 中要真正理解函数将会成为你最厉害的武器,如此重要,事实上,这一章以及接下来的两章都致力于彻底理解 javascript 中的函数。原:Most importantly, in JavaScript, functions are first-class objects; that is, they coexistwith, and can be treated like, any other JavaScript object. Just like the more mundaneJavaScript data types, they can be referenced by variables, declared with literals, andeven passed as function parameters.译:最重要的是,在 javascript 中,函数是一级对象,也就是说,他是并存,也可以当作是 javascript 的另一个对象,就像最基本的 javascript 数据类型,他们能被引用、声明字面值,甚至是作为函数的参数。原:The fact that JavaScript treats functions as first-class objects is going to be importanton a number of levels, but one significant advantage comes in the form of code terseness.To take a sneak-peek ahead to some code that well examine in greater depth insection 3.1.2, consider this imperative code (in Java) that performs a collection sort:Arrays.sort(values,new Comparator()public int compare(Integer value1, Integer value2) return value2 - value1;);译:事实上,javascript 将函数处理为一级对象是十分重要,在一定程度上讲,另一个优点是将代码简洁化。先取一段 sneak-peek 代码, 我们将在一定程度上检查 3.1.2 节,执行一组排序的必要代码(java 中)如下:Arrays.sort(values,new Comparator()public int compare(Integer value1, Integer value2) return value2 - value1;);原:Heres the JavaScript equivalent written using a functional approach:values.sort(function(value1,value2) return value2 - value1; );Dont be too concerned if the notation seems oddyoull be an old hand at it by theend of this chapter. We just wanted to give you a glimpse of one of the advantages thatunderstanding JavaScript as a functional language will bring to the table.This chapter will thoroughly examine JavaScripts focus on functions and give youa sound basis on which to bring your JavaScript code to a level that any master wouldbe proud of.译:下面是使用 javascript 函数方法,实现相同效果的代码:values.sort(function(value1,value2) return value2 - value1; );如果有看似奇怪的符号不要太注意 在这章结束之前,你会经常看到他,我们只想要让你看一下将 javascript 作为函数式语言带来便利的一大优点。本章将彻底讲解 javascript 函数,向你展示各种大师级的代码,让你有一个良好的基础。原:3.1 Whats with the functional difference?How many times have you heard someone moan, “I hate JavaScript”?Were willing to bet that nine times out of ten (or perhaps even more), this is adirect consequence of someone trying to use JavaScript as if it were another languagethat the lamenter is more familiar with, and that theyre frustrated by the fact thatits not that other language. This is probably most common with those coming toJavaScript from a language such as Java, a decidedly nonfunctional language, but onethat a lot of developers learn before their exposure to JavaScript.译:3.1 关于功能的区别是什么我们总听到有人抱怨:“我讨厌 javascript”?我敢说:十次有九次(甚至更多) ,这是他们试图使用 javascript 就像是另一种语言的后果,悲观者更熟悉,而且他们沮丧的是没有其他语言。这可能是最常见的 javascript 与 java 一个非功能性语言。但是开发者学习之前接触 javascript 的想法。原:译:让事情更糟糕的是很多开发者直接从名字选择 javascript。没有过分说明命名决定背后的历史。如果仍保留 livescript 这个名字,将减少开发者对这个的这个误解。因为就像一个很经典玩笑,在图 3.1 javascript 与 java 的关系就像 hamburger 与 ham 的关系。只是名字有部分相同而已。原:TIP For more information on how JavaScript got its name, see /wiki/JavaScript#History, /web/20070916144913//newsref/pr/newsrelease67.html, and /questions/2018731/why-is-javascript-called-javascript-since-ithas-nothing-to-do-with-java. If you follow these links, they indicate that theintent was to identify JavaScript as a complement to Java, rather than somethingthat shared its characteristics.Hamburgers and ham are both foods that are meat products, just as JavaScript andJava are both programming languages with a C-influenced syntax. But other thanthat, they dont have much in common and are fundamentally different right downto their DNA.译:小技巧:这里有很多信息关于为什么叫 javascript:/wiki/JavaScript#History /web/20070916144913//newsref/pr/newsrelease67.html/questions/2018731/why-is-javascript-called-javascript-since-ithas-nothing-to-do-with-java. 如果你看了这些连接,他们将展示旨在定义 javascript 作为 java 的一种补充而不是共享其特征。Hamburgers 和 ham 都是肉类食物,就像 javascript 和 java 都是与 c语法将近的程序语言,除此之外他们没有其他共同点,他们有完全不同的,所以它们是完全不一样的原:NOTE Another factor that plays into some developers poor initial reaction toJavaScript may be that most developers are introduced to JavaScript in thebrowser. Rather than reacting to JavaScript, the language, they may be recoilingfrom the JavaScript bindings to the DOM API. And the DOM API . well,lets just say that it isnt going to win any Friendliest API of the Year awards. Butthats not JavaScripts fault.Before we learn about how functions are such a central and key concept in JavaScript,lets consider why the functional nature of JavaScript is so important, especially forcode written for the browser.译:注意:另外一种导致开发者缺乏对 javascript 最初意识的因素是大多数开发者都是基于浏览器介绍 javascript,而不是直接针对 javascript,他们可能将 javascript 绑定到 DOM API 上.我只能说 javascript 没有友好的API 奖项不是 javascript 的错 。在我们学习函数为如此重要关键的概念时,让我们先思考一下,为什么javascript 中函数的性质如此重要,特别是对编写代码的浏览器。原:3.1.1 Why is JavaScripts functional nature important?If youve done any amount of scripting in a browser, you probably know all that weregoing to discuss in this section, but lets go over it anyway to make sure were all usingthe same vernacular.One of the reasons that functions and functional concepts are so important inJavaScript is that the function is the primary modular unit of execution. Except forthe inline script that runs while the markup is being evaluated, all of the script codethat well write for our pages will be within a function.NOTE Back in the Dark Ages, inline script was used to add dynamism to pagesvia document.write(). These days, document.write() is considered a dinosaurand its use isnt recommended. There are better ways to make pages dynamic,such as the use of server-side templating, client-side DOM manipulation, or ahealthy combination of both.译:3.1.1 为什么 javascript 中函数的性质如此重要如果你已经在浏览器中写大量的脚本,你可能会知道我们这节所讨论的,但是让我们去克服他,无论如何确保我们都是用同样的术语在 javascript 中,函数以及函数的概念是如此重要的原因之一是函数是主要模块的执行单位,除了内联脚本运行的函数会被评估,所有的脚本代码我们会写在一个函数里。注意: 以前,内联脚本是用来向页面添加动态效果通过 document.write() 。现在,document.write()被当作是一种恐龙,不建议使用。最好的让网页动态方法是使用服务器模板,客户端 DOM 操作或者两者合理结合。原:Because most of our code will run as the result of a function invocation, well see thathaving functions that are versatile and powerful constructs will give us a great deal offlexibility and sway when writing our code. Well spend the rest of this chapter examiningjust how the nature of functions as first-class objects can be exploited to ourgreat benefit.Now, thats the second time weve used the term “first-class object,” and its animportant concept, so before we go on, lets make sure we know what it really means.译:因为我们的大部分代码将运行作为函数调用的结果,我们将会看到在编写代码时,通用的函数和强大的结构会给我们一个很大的灵活性和影响力。本章接下来我们将探索函数作为一级对象是如何创造最大效益的。现在,这是第二次我们使用术语 “一级对象,”,这是一个重要的概念,所以在我们继续之前,让我们确保我们知道它的真正含义。原:FUNCTIONS AS FIRST-CLASS OBJECTSObjects in JavaScript enjoy certain capabilities: They can be created via literals. They can be assigned to variables, array entries, and properties of other objects. They can be passed as arguments to functions. They can be returned as values from functions. They can possess properties that can be dynamically created and assigned.Functions in JavaScript possess all of these capabilities and are thus treated like anyother object in the language. Therefore, we say that theyre first-class objects.And more than being treated with the same respect as other object types, functionshave a special capability in that they can be invoked.That invocation is frequently discharged in an asynchronous manner, so lets talk alittle about why that is.译:函数作为一级对象在javascript中对象有以下几个特征1.可以通过字面量创建。2.可以分配给变量、数组和其他对象的属性。3.可以作为参数传给函数4.可以作为函数的返回值5.可以拥有可以动态地创建并分配的属性在 javascript 中函数也有以上特征,而且就像语言中的其他对象,因此我们说他是一级对象。而且,受到了更多的关注被作为其他对象类型,所以让我么探讨一下为什么会出现这种情况。原:THE BROWSER EVENT LOOPIf youve done any programming to create graphical user interface (GUI) desktopapplications, youll know that most are written in a similar fashion: Set up the user interface Enter a loop waiting for events to occur Invoke handlers (also called listeners) for those eventsProgramming for the browser is no different, except that our code isnt responsiblefor running the event loop and dispatching events; the browser handles that for us.Our responsibility is to set up the handlers for the various events that can occur inthe browser. These events are placed in an event queue (a FIFO list; more on thatlater) as they occur, and the browser dispatches these events by invoking any handlersthat have been established for them.Because these events happen at unpredictable times and in an unpredictableorder, we say that the handling of the events, and therefore the invocation of theirhandling functions, is asynchronous.译:浏览器的消息线程如果你做过任何创建图形用户界面(GUI)桌面应用程序的编程,你就会知道,大多数都是用类似的方式:1.创建用户接口2.进入消息线程等待事件发生3.为这些事件调用处理(也叫监听)除了我们的代码并不负责运行事件循环和调度事件,与浏览器处理编程没有什么不同。我们的责任是在浏览器中,建立可能发生的各种事件的处理程序。这些事件被放置在一个事件队列中(FIFO列表; 更多后来) 发生时, 浏览器将调用这些已经建立的事件处理程序因为这些事件发生在不可预测的时间和不可预知的顺序,也就是我们说的事件处理,因此调用这些处理函数是异步的。原:The following types of events can occur, among others: Browser events, such as when a page is finished loading or when its to beunloaded Network events, such as responses to an Ajax request User events, such as mouse clicks, mouse moves, or keypresses Timer events, such as when a timeout expires or an interval firesThe vast majority of our code executes as a result of such events. Consider the following:function startup()/* do something wonderful */window.onload = startup;译:以下的事件类型中可能发生异步:1.浏览器事件,如:当我们加载完一个网页,或者未加载完的时候。2.Network事件,如:ajax请求3.用户事件,如:鼠标点击,移动,按下4.定时器时间:如timeout,interval绝大多数的我们的代码执行此类事件的结果。思考下面代码:function startup()/* do something wonderful */ window.onload = startup;原:Here, we establish a function to serve as a handler for the load event. The establishingstatement executes as part of the inline script (assuming it appears at the top level andnot within any other function), but the wonderful things that were going to do insidethe function dont execute until the browser finishes loading the page and fires off aload event.In fact, we can simplify this to a single line if we like. Consider this:window.onload = function() /* do something wonderful */ ;(If the notation used to create the function looks odd to you, be assured that well bemaking it crystal clear in section 3.2.)译:在这里,我们建立一个函数作为 load事件的处理程序。创建语句执行作为内联脚本的一部分(假设它出现在顶层而且没有任何其他函数),但精彩的是在内部函数,直到浏览器加载完页面才触发 load事件。事实上,我们可以简化这一 行, 如果我们喜欢。考虑一下 :window.onload = function() /* do something wonderful */ ;(如果符号用于创建函数看起来奇怪, 放心,我们会在 3.2 节详细讲解)。原:Unobtrusive JavaScriptThe approach of assigning a function, named or otherwise, to the onload property ofthe window instance may not be the way that youre used to setting up a load handler.You may be more accustomed to using the onload attribute of the tag.Either approach achieves the same effect, but the window.onload approach is vastlypreferred by JavaScript ninjas as it adheres to a popular principle known as unobtrusiveJavaScript.Remember when the advent of CSS pioneered the moving of style information out ofthe document markup? Few would argue that segregating style from structure was abad move. Unobtrusive JavaScript does the same thing for behavior, moving scriptsout of the document markup.This results in pages having their three primary componentsstructure, style, andbehavior nicely partitioned into their own locations. Structure is defined in the documentmarkup, style in elements or external style sheets, and behavior inblocks or external script files.You wont see any script embedded into document markup in the examples in thisbook, unless its to make a specific point or to vastly simplify the example.译:把 JavaScript 从 html 中分离出去(Unobtrusive)指定一个函数的方法,命名或其他 ,对于window的 onload属性实例,你可能不习惯以这种方式建立一个load处理程序。而更习惯在 中使用的onload属性。其他方法也可以达到同样的效果,但是 window.onload 方法是JavaScript 忍者这本书的首选, 因为它遵循一个受欢迎的原则称为低调的JavaScript。还记得CSS倡导将样式信息与文档标记分离吗? 很少有人会认为,将样式从结构分离是一个糟糕的举动。低调的JavaScript也采取同样的方式, 将脚本与文档标记分离开。这导致页面由三部分组成:结构,样式, 和行为 很好地划分自己的位置。结构在文档标记中定义,样式在 元素中或者外部样式表,行为脚本块或外部脚本文件。在这本书中,你不会看到任何脚本嵌入到文档标记的示例,除非是一个特殊的或者简单的例子。原:Its important to note that the browser event loop is single-threaded. Every event thatsplaced into the event queue is handled in the order that its placed onto the queue.This is known as a FIFO list (first-in, first-out), or perhaps a silo to the old-timers. Eachevent is processed in its own “turn,” and all other events have to wait until the currentevents turn is over. Under no circumstances are two handlers executing simultaneouslyin separate threads.Think of a line at the bank. Everyone gets into a single line and has to wait theirturn to be “processed” by the tellers. But with JavaScript, theres only one teller windowopen! So the customers only get processed one at a time, as their turn comes. All ittakes is one person, who thinks its appropriate to do their financial planning for thefiscal year while theyre at the tellers window (weve all run into them!), to gum upthe whole works.译:最需要注意的是浏览器消息线程是单线程的。每一个事件的执行顺序是放到消息队列处理的顺序。这就是所谓的FIFOlist(先入先出)。每个事件都是轮流处理的,其他事件必须等到当前事件的结束才开始处理。绝不会在单独的线程同时执行两个处理程序。想想在银行排队,每个人都进一列队上等待出纳员操作。但对于JavaScript,只有一个出纳员窗口打开! 因此,一次只处理一个客户,轮流处理。一切只有一个人处理,他认为这是合理的的财务规划对于财政年度, 而如果他们都在出纳员的窗口(我们都遇到他们 !),所有的事情就会乱成一遭。原:Well explore this execution model, and ways of dealing with its challenges, in greatdepth in chapter 8.A vastly simplified overview of this process is shown in figure 3.2.This concept is central to on-page JavaScript, and its something well see again andagain throughout the examples in this book: code is set up in advance in order toexecute at a later time. Except for inline setup code, the vast majority of the code thatwe place onto a page is going to execute as the result of an event (as part of the “Processevent” box in figure 3.2).Its important to note that the browser mechanism that puts the events onto thequeue is external to this event loop model. The processing necessary to determinewhen events have occurred and to push them onto the event queue doesnt participatein the thread thats handling the events.For example, when the end user waves the mouse around on the page, the browserwill detect these motions and push a bunch of mousemove events onto the event queue.The event loop will eventually come across these events and trigger any handlersestablished for that type of event.Such event handlers are examples of a more general concept known as callbackfunctions. Lets explore that very important concept.译:(图略)我们将探讨这种执行模式,以及其挑战的方法, 在第 8章将更加深入的探讨。如图3.2所示,简单概述了这一过程。这是网页JavaScript的核心概念,这个例子将贯穿全文: 代码虽然提前设置的但却在稍后的时间执行。除了内联创建代码, 绝大多数的代码我们将到一个网页运行,作为一个事件的结果执行(如在图3.2,作为“Process event”框的一部分)。最值得注意的事,浏览器的机制是把事件放到队列是外部消息队列模型。这个过程决定了事件的发生以及把他们放到事件队列却不参与事件处理的线程。例如,当最终用户在页面上的移动鼠标 ,浏览器将检测这些动作 ,把一群mousemove事件到事件队列中。消息队列最终会遇到这些事件并触发这些处理程序。原:THE CALLBACK CONCEPTWhenever we set up a function to be called at a later time, whether by the browser orother code, were setting up what is termed a callback. The term stems from the factthat we establish a function that some other code will later “call back” into at anappropriate point of execution.Callbacks are an essential part of using JavaScript effectively, and were about tolook at a real-world example of how callbacks are used. But its a tad complex, sobefore we dive into it, lets strip the callback concept completely naked and examine itin its simplest form.Well see callbacks used extensively as event handlers throughout the remainder ofthis book, but event handlers are just one example of callbacks; we can even employcallbacks ourselves in our own code. Heres an illuminating example of a completelyuseless function that accepts a reference to another function as a parameter and callsthat function as a callback:function useless(callback) return callback(); 译:回调函数的概念每当我们创建一个要在以后的时间调用(无论是通过浏览器或其他的代码调用)的函数,我们称之为回调函数。一词源于这样一个事实:我们建立一个函数,其他一些代码将会在适当的点再来执行。回调是有效使用JavaScript 必不可少的一部分, 我们要通过一个真实的例子看看如何使用回调函数但它是有点复杂,所以我们深入之前 ,让我们脱离回调的概念,以最简单的形式理解它。我们会发现在本书的一下部分事件处理会广泛的使用回调函数,但事件处理只是回调函数的一个实例;我们应该我们自己的代码中运用回

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论