The Javascript Language Chris Morgan North Texas PC Users Group June 2010 Background

Total Page:16

File Type:pdf, Size:1020Kb

The Javascript Language Chris Morgan North Texas PC Users Group June 2010 Background The JavaScript Language Chris Morgan North Texas PC Users Group June 2010 Background • JavaScript originated in 1995 by Netscape • Microsoft version was called Jscript • Standardization happened in 1998 – called ECMAScript • WiKiPedia: “JavaScript is a dialect of the ECMAScript standard and is characterized as a dynamic, weakly-typed, prototype-based language with first-class functions.” Basics • JavaScript is a true object-oriented language • JavaScript has no “classes”, liKe in C# or Java • A JavaScript object is a collection of name/value pairs called “properties” (an “associative array”) • Supports arrays and functions • Arrays can have values of different “types”, including functions • Functions are objects • Case-sensitive language • Lines end with a semi-colon • Variables are loosely typed – inferred at runtime • All data types are objects Objects • var book = new Object(); • var book = {}; • {} represents an “empty” object • Once created, objects can be expanded at any time, by adding properties on the fly • booK.title = “jQuery In Action” • Creates the property “title” • Assigns a value to this new property • Can be anywhere in the code, executed at any time • for(var prop in book){alert(“Name: ” + prop + “, “Value: ” + book[prop])}; • Property values of objects also have implied properties and methods JavaScript Data Types • Number • String • Date • Boolean • Math • Array • RegExp • Function String Object • var txt = new String(string); or • var txt = string; • Implied properties • Length • Implied methods • HTML: bold() big() fixed() fontcolor() fontsize() italics() linK(url) small() striKe() sub() sup() sub() • Object: charAt() concat(str2, str3, …) indexOf() lastIndexOf() match() replace() search() sliced() split() substring() substr() toLowerCase() toUpperCase() Other Data Types • var num = new Number(6.3); • var num = 6.3; • Implied methods: • toString() • toFixed(x) • toPrecision(x) • toExponential() • var d = new Date() • var b = new Boolean() Arrays • A JavaScript array is an ordered collection of values that can be of different types • var arr = new Array(); • var arr = []; • Similar to generic lists in .NET • New array elements can be added at any time • Array elements can be strings, numbers, dates, booleans, objects, functions, and child arrays • No space is pre-allocated for array elements JavaScript Functions • Treated as an object – a “first-class function” • Functions can be instantiated (created), returned by other functions, stored as an array element or object property, or assigned to a variable • Normal declaration of a function: function myFunc(parm1, parm2) { parm1 = parm1 + parm2; return parm1; } • A function with no paramters still uses the parentheses function myFunc() {return “Some Text”;}; • Defines an object “calc”: var calc {}; • Adds a function property to the object just created; a method: calc.add = function(a,b){return (a + b)}; • Use of the function: var c = calc.add(2,3); • A JavaScript function stored as an object property is called a “method” • Functions can be nested JavaScript Functions • All functions are executed as a method of some object • The ‘this’ Keyword is a reference to the object which is executing the method • 1) Global object is ‘this’ when function is defined in the page as a global function • 2) DOM Event Handler – ‘this’ references the DOM element that hooKed up the event • If you are in an HTML element nested in another element having an event and you clicK on the inner element, the clicK event will “bubble” up to the outer element that subscribed to the event and fire off. ‘this’ will refer to the outer element, not the element which triggered the event. • 3) Constructor function – ‘this’ refers to the object being created • Properties of objects cannotbe private in scope. JavaScript Functions • Anonymous functions • You can define and use a function without giving it a name. Use the Keyword ‘function’ instead of a name. • Example: you can assign a function to a variable and execute this variable liKe a function: var myFunc = function(parm1, parm2){parm1 = parm1 + parm2; return parm1;} • Example: when you are assigning a function to a ‘clicK’ event, you can just define the function there instead of referencing one that was already declared • Closure • When nesting functions, variables declared in an outer function can be seen by the inner functions JavaScript Functions • You can assign a function to a variable or an object property – a pointer – and use the pointer just liKe the function. So, you can have multiple ways to execute the same function. If the function changes, then all the pointers (variables) have the new functionality. var c; function myFunc(p1, p2){return p1 + p2}; var abc = myFunc; c = abc(“Hello”, “World”); • Since a function is an object, you can create properties for it. Javascript - first class functions functional programing style Javascript: • supports passing functions as arguments to other functions, • returning them as the values from other functions, • assigning them to variables • storing them in data structures • supports for anonymous functions (function literals) The names of functions do not have any special status; they are trated like ordinary variables with a function type Javascript closure (1) – var access in functions local access - inside global access – outside JavaScriptvariables can belong to the local or global scope. Global variables can be made local (private) with closures. Javascript closure (2) – counter dilemma Javascript closure (3) – nested function private variable self-invoKing function (immediately-invoKed function expressions) nested function closure A closure is a function having access to the parent scope, even after the parent function has closed. Javascript module pattern (1) – anonymous closure (function () { // ... all vars and functions are in this scope only // still maintains access to all globals }()); the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application Javascript module pattern (2) Internal state var MyModule = (function () { var my = {}, private method privateVariable = 1; global var function privateMethod() { // ... } property my.moduleProperty = 1; my.moduleMethod = function () { // ... }; method return my; }()); anonymous function return value Javascript – prototype • A prototypeis a worKing object instance. • Objects inherit directly from other objects. • Javascriptfavor object composition over class inheritance. Javascript – prototypal inheritance • Prototypedelegation - an object may have a linK to a prototypefor delegation. If a property is not found on the object, the looKup is delegated to the delegate prototype, which may have a linK to its own delegate prototype, and so on up the chain until youarrive at `Object.prototype`, which is the root delegate. • Concatenative inheritance - The process of inheriting features directly from one object to another by copying the source objects properties. In JavaScript, source prototypes are commonly referred to as mixins. • Functional inheritance- any function can create an object. When that function is not a constructor(or `class`), it’s called a factory function. Functional inheritance worKs by producing an object from a factory, and extending the produced object by assigning properties to it directly (using concatenative inheritance). Javascript – example (1) function object Javascript – example (2) Javascript – example (3) arguments – special var variadic function Javascript – example (4) – this.
Recommended publications
  • Declare Function Inside a Function Python
    Declare Function Inside A Function Python Transisthmian and praetorian Wye never ensphere helter-skelter when Shawn lord his nightshade. Larboard Hal rumors her dizziesacapnia very so encouragingly actinally. that Colbert aurifies very inferentially. Kenyan Tad reframes her botts so irefully that Etienne Closures prove to it efficient way something we took few functions in our code. Hope you have any mutable object. Calling Functions from Other Files Problem Solving with Python. What embassy your website look like? Then you can declare any result of a million developers have been loaded? The coach who asked this gas has marked it as solved. We focus group functions together can a Python module see modules and it this way lead our. What are Lambda Functions and How to Use Them? It working so art the result variable is only accessible inside the function in. Variables inside python node, learn more detail, regardless of instances of a program demonstrates it. The python function inside another, which start here, and beginners start out. Get code examples like python define a function within a function instantly right anytime your google search results with the Grepper Chrome. The function by replacing it contains one function start here are discussed: how do not provide extremely cost efficient as their name? How to the page helpful for case it requires you can declare python data science. Each item from the python function has arbitrary length arguments must first, but are only the output is simply the function to. We declare their perfomance varies with the gathered arguments using a wrapped the arguments does the computed fahrenheit to declare function inside a function python? List of python can declare a function inside a million other functions we declare function inside a function python.
    [Show full text]
  • Explain Function Declaration Prototype and Definition
    Explain Function Declaration Prototype And Definition ligatedreprobated,Sidearm feminizes and but road-hoggish Weylin vengefully. phonemic Roderich nose-dived never reckons her acetones. his carat! Unfabled Dubitative Dewey and ill-equippedclangour, his Jerzy stringer See an example of passing control passes to function declaration and definition containing its prototype Once which is declared in definition precedes its definition of declaring a body of. Check out to explain basic elements must be explained below. They gain in this browser for types to carry out into parts of functions return statement of your pdf request that same things within your program? Arguments and definitions are explained below for this causes an operator. What it into two. In definition and declare a great; control is declared in this parameter names as declaring extern are explained in expressions and ms student at runtime error. Classes and definition was tested in a, and never executed but it will be called formal parameters are expanded at later. There are definitions to prototype definition tells the value method of an example are a function based on the warnings have had been declared. Please enter valid prototype definition looks a function definitions affects compilation. In this method is fixed words, but unlike references or rethrow errors or constants stand out its argument is only if more code by subclasses. How do is the variable of the three basic behavior of variable num to explain actual values of yours i desired. Also when a function num_multiplication function and definition example. By value of the definitions are explained in the nested function, the program passes to.
    [Show full text]
  • The Power of Interoperability: Why Objects Are Inevitable
    The Power of Interoperability: Why Objects Are Inevitable Jonathan Aldrich Carnegie Mellon University Pittsburgh, PA, USA [email protected] Abstract 1. Introduction Three years ago in this venue, Cook argued that in Object-oriented programming has been highly suc- their essence, objects are what Reynolds called proce- cessful in practice, and has arguably become the dom- dural data structures. His observation raises a natural inant programming paradigm for writing applications question: if procedural data structures are the essence software in industry. This success can be documented of objects, has this contributed to the empirical success in many ways. For example, of the top ten program- of objects, and if so, how? ming languages at the LangPop.com index, six are pri- This essay attempts to answer that question. After marily object-oriented, and an additional two (PHP reviewing Cook’s definition, I propose the term ser- and Perl) have object-oriented features.1 The equiva- vice abstractions to capture the essential nature of ob- lent numbers for the top ten languages in the TIOBE in- jects. This terminology emphasizes, following Kay, that dex are six and three.2 SourceForge’s most popular lan- objects are not primarily about representing and ma- guages are Java and C++;3 GitHub’s are JavaScript and nipulating data, but are more about providing ser- Ruby.4 Furthermore, objects’ influence is not limited vices in support of higher-level goals. Using examples to object-oriented languages; Cook [8] argues that Mi- taken from object-oriented frameworks, I illustrate the crosoft’s Component Object Model (COM), which has unique design leverage that service abstractions pro- a C language interface, is “one of the most pure object- vide: the ability to define abstractions that can be ex- oriented programming models yet defined.” Academ- tended, and whose extensions are interoperable in a ically, object-oriented programming is a primary focus first-class way.
    [Show full text]
  • Fast Functional Simulation with a Dynamic Language
    Fast Functional Simulation with a Dynamic Language Craig S. Steele and JP Bonn Exogi LLC Las Vegas, Nevada, USA [email protected] Abstract—Simulation of large computational systems-on-a-chip runtime, rather than requiring mastery of a simulator-specific (SoCs) is increasing challenging as the number and complexity of domain-specific language (DSL) describing the binary-code components is scaled up. With the ubiquity of programmable translation task. components in computational SoCs, fast functional instruction- set simulation (ISS) is increasingly important. Much ISS has been done with straightforward functional models of a non-pipelined II. RELATED WORK fetch-decode-execute iteration written in a low-to-mid-level C- Interpretative instruction-set simulators (ISS) abound, with family static language, delivering mid-level efficiency. Some ISS various levels of detail in the processor model. The sim-fast programs, such as QEMU, perform dynamic binary translation simulator from SimpleScalar LLC is a well-known to allow software emulation to reach more usable speeds. This representative of a straightforward C-based fetch-decode- relatively complex methodology has not been widely adopted for execute iterative ISS interpreter, achieving more than 10 MIPS system modeling. for basic functional instruction-set-architecture (ISA) simulation [1]. This naïve approach is a software analog of a We demonstrate a fresh approach to ISS that achieves non-pipelined hardware processor implementation, simple but performance comparable to a fast dynamic binary translator by slow. exploiting recent advances in just-in-time (JIT) compilers for dynamic languages, such as JavaScript and Lua, together with a Many variations of binary translation for ISS exist, specific programming idiom inspired by pipelined processor translating instructions in the simulated ISA into code design.
    [Show full text]
  • Python Scope 3
    Class XII Computer Science : Python (Code: 083) Chapter: Functions Chapter : Functions Topics Covered: 1. Functions: scope Learning Outcomes: In this tutorial, we’ll learn: 1. What scopes are and how they work in Python 2. Why it’s important to know about Python scope 3. What is the LEGB rule 4. Using Python global statement and nonlocal statement Youtube Video Tutorial: 1. https://www.youtube.com/watch?v=07w3KkQqgi0 2. https://www.youtube.com/watch?v=R5uLNhRaGD0 3. https://www.youtube.com/watch?v=NdlWHlEgTn8 Python Scope Scope of a name (variables, functions etc) is the area of code where the name is created and can be used or accessed. A variable is only available from inside the region it is created. This is called scope. The scope of a name or variable depends on the place in our code where we create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule. LEGB stand for Local, Enclosing, Global, and Built-in scopes. These are the names of Python scopes and also the sequence of steps that Python follows when accessing names in a program. Therefore in python there are 4 scopes 1. Local scope 2. Enclosing scope 3. Global scope 4. Built in scope 1 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. Example A variable created inside a function is available inside that function only: def myfunc(): x= 300 print(x) myfunc() print(x) # error, because x is created inside myfunc(), so it is available inside that function only Enclosing Scope (Function Inside a Function) A variable is available inside that function only in which it is created.
    [Show full text]
  • 210 CHAPTER 7. NAMES and BINDING Chapter 8
    210 CHAPTER 7. NAMES AND BINDING Chapter 8 Expressions and Evaluation Overview This chapter introduces the concept of the programming environment and the role of expressions in a program. Programs are executed in an environment which is provided by the operating system or the translator. An editor, linker, file system, and compiler form the environment in which the programmer can enter and run programs. Interac- tive language systems, such as APL, FORTH, Prolog, and Smalltalk among others, are embedded in subsystems which replace the operating system in forming the program- development environment. The top-level control structure for these subsystems is the Read-Evaluate-Write cycle. The order of computation within a program is controlled in one of three basic ways: nesting, sequencing, or signaling other processes through the shared environment or streams which are managed by the operating system. Within a program, an expression is a nest of function calls or operators that returns a value. Binary operators written between their arguments are used in infix syntax. Unary and binary operators written before a single argument or a pair of arguments are used in prefix syntax. In postfix syntax, operators (unary or binary) follow their arguments. Parse trees can be developed from expressions that include infix, prefix and postfix operators. Rules for precedence, associativity, and parenthesization determine which operands belong to which operators. The rules that define order of evaluation for elements of a function call are as follows: • Inside-out: Evaluate every argument before beginning to evaluate the function. 211 212 CHAPTER 8. EXPRESSIONS AND EVALUATION • Outside-in: Start evaluating the function body.
    [Show full text]
  • The Principles of Object-Oriented Javascript Zakas
    TAKETAKE CONTROLCONTROL OFOF Foreword by Cody Lindley, Best-selling Author and Principal Frontend Architect JAVASCRIPT THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT JAVASCRIPT THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT THETHE PRINCIPLESPRINCIPLES OFOF OBJECTSOBJECTS at TandemSeven OBJECT-ORIENTEDOBJECT-ORIENTED If you’ve used a more traditional object-oriented • How to define your own constructors JAVASCRIPTJAVASCRIPT language, such as C++ or Java, JavaScript probably • How to work with and understand prototypes doesn’t seem object-oriented at all. It has no concept of classes, and you don’t even need to define any • Inheritance patterns for types and objects objects in order to write code. But don’t be fooled — The Principles of Object-Oriented JavaScript will leave NICHOLAS C. ZAKAS JavaScript is an incredibly powerful and expressive even experienced developers with a deeper understand- object-oriented language that puts many design ing of JavaScript. Unlock the secrets behind how objects decisions right into your hands. work in JavaScript so you can write clearer, more In The Principles of Object-Oriented JavaScript, flexible, and more efficient code. Nicholas C. Zakas thoroughly explores JavaScript’s object-oriented nature, revealing the language’s A B O U T T H E A U T H O R unique implementation of inheritance and other key characteristics. You’ll learn: Nicholas C. Zakas is a software engineer at Box and is known for writing on and speaking about the latest • The difference between primitive and reference in JavaScript best practices. He honed his experience values during his five years at Yahoo!, where he was principal • What makes JavaScript functions so unique frontend engineer for the Yahoo! home page.
    [Show full text]
  • Evolution and Composition of Object-Oriented Frameworks
    Evolution and Composition of Object-Oriented Frameworks Michael Mattsson University of Karlskrona/Ronneby Department of Software Engineering and Computer Science ISBN 91-628-3856-3 © Michael Mattsson, 2000 Cover background: Digital imagery® copyright 1999 PhotoDisc, Inc. Printed in Sweden Kaserntryckeriet AB Karlskrona, 2000 To Nisse, my father-in-law - who never had the opportunity to study as much as he would have liked to This thesis is submitted to the Faculty of Technology, University of Karlskrona/Ronneby, in partial fulfillment of the requirements for the degree of Doctor of Philosophy in Engineering. Contact Information: Michael Mattsson Department of Software Engineering and Computer Science University of Karlskrona/Ronneby Soft Center SE-372 25 RONNEBY SWEDEN Tel.: +46 457 38 50 00 Fax.: +46 457 27 125 Email: [email protected] URL: http://www.ipd.hk-r.se/rise Abstract This thesis comprises studies of evolution and composition of object-oriented frameworks, a certain kind of reusable asset. An object-oriented framework is a set of classes that embodies an abstract design for solutions to a family of related prob- lems. The work presented is based on and has its origin in industrial contexts where object-oriented frameworks have been developed, used, evolved and managed. Thus, the results are based on empirical observations. Both qualitative and quanti- tative approaches have been used in the studies performed which cover both tech- nical and managerial aspects of object-oriented framework technology. Historically, object-oriented frameworks are large monolithic assets which require several design iterations and are therefore costly to develop. With the requirement of building larger applications, software engineers have started to compose multiple frameworks, thereby encountering a number of problems.
    [Show full text]
  • User Manual for PLC Programming With
    User Manual for PLC Programming with CoDeSys 2.3 Copyright ã 1994, 1997, 1999, 2001,2002, 2003 by 3S - Smart Software Solutions GmbH All rights reserved. We have gone to great lengths to ensure this documentation is correct and complete. However, since it is not possible to produce an absolutely error-free text, please feel free to send us your hints and suggestions for improving it. Trademark Intel is a registered trademark and 80286, 80386, 80486, Pentium are trademarks of Intel Corporation. Microsoft, MS and MS-DOS are registered trademarks, Windows is a trademark of Microsoft Corporation. Publisher 3S - Smart Software Solutions GmbH Fischerstraße 19 D-87435 Kempten Tel. +49 831 5 40 31 - 0 Fax +49 831 5 40 31 – 50 Last update 20.08.2003 Version 2.0 Content 1 A Brief Introduction to CoDeSys 1-1 1.1 What is CoDeSys .................................................................................................1-1 1.2 Overview of CoDeSys Functions... ......................................................................1-1 1.3 Overview on the user documentation for CoDeSys.............................................1-3 2 What is What in CoDeSys 2-1 2.1 Project Components.............................................................................................2-1 2.2 Languages... .........................................................................................................2-8 2.2.1 Instruction List (IL)... .............................................................................................2-8 2.2.2 Structured
    [Show full text]
  • Obstacl: a Language with Objects, Subtyping, and Classes
    OBSTACL: A LANGUAGE WITH OBJECTS, SUBTYPING, AND CLASSES A DISSERTATION SUBMITTED TO THE DEPARTMENT OF COMPUTER SCIENCE AND THE COMMITTEE ON GRADUATE STUDIES OF STANFORD UNIVERSITY IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF DOCTOR OF PHILOSOPHY By Amit Jayant Patel December 2001 c Copyright 2002 by Amit Jayant Patel All Rights Reserved ii I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. John Mitchell (Principal Adviser) I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. Kathleen Fisher I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. David Dill Approved for the University Committee on Graduate Studies: iii Abstract Widely used object-oriented programming languages such as C++ and Java support soft- ware engineering practices but do not have a clean theoretical foundation. On the other hand, most research languages with well-developed foundations are not designed to support software engineering practices. This thesis bridges the gap by presenting OBSTACL, an object-oriented extension of ML with a sound theoretical basis and features that lend themselves to efficient implementation. OBSTACL supports modular programming techniques with objects, classes, structural subtyping, and a modular object construction system. OBSTACL's parameterized inheritance mechanism can be used to express both single inheritance and most common uses of multiple inheritance.
    [Show full text]
  • What Is Object-Oriented Perl?
    This is a series of extracts from Object Oriented Perl, a new book from Manning Publications that will be available in August 1999. For more information on this book, see http://www.manning.com/Conway/. What is object-oriented Perl? Object-oriented Perl is a small amount of additional syntax and semantics, added to the existing imperative features of the Perl programming language. Those extras allow regular Perl packages, variables, and subroutines to behave like classes, objects, and methods. It's also a small number of special variables, packages and modules, and a large number of new techniques, that together provide inheritance, data encapsulation, operator overloading, automated definition of commonly used methods, generic programming, multiply-dispatched polymorphism, and persistence. It's an idiosyncratic, no-nonsense, demystified approach to object-oriented programming, with a typically Perlish disregard for accepted rules and conventions. It draws inspiration (and sometimes syntax) from many different object-oriented predecessors, adapting their ideas to its own needs. It reuses and extends the functionality of existing Perl features, and in the process throws an entirely new slant on what they mean. In other words, it's everything that regular Perl is, only object-oriented. Using Perl makes object-oriented programming more enjoyable, and using object- oriented programming makes Perl more enjoyable too. Life is too short to endure the cultured bondage-and-discipline of Eiffel programming, or to wrestle the alligators that lurk in the muddy semantics of C++. Object-oriented Perl gives you all the power of those languages, with very few of their tribulations. And best of all, like regular Perl, it's fun! Before we look at object orientation in Perl, let’s talk about what object orientation is in general..
    [Show full text]
  • Lecture #24: Achieving Runtime Effects—Functions
    Lecture #24: Achieving Runtime Effects—Functions • Language design and runtime design interact. Semantics of func- tions make good example. • Levels of function features: 1. Plain: no recursion, no nesting, fixed-sized data with size known by compiler. 2. Add recursion. 3. Add variable-sized unboxed data. 4. Allow nesting of functions, up-level addressing. 5. Allow function values w/ properly nested accesses only. 6. Allow general closures. 7. Allow continuations. • Tension between these effects and structure of machines: – Machine languages typically only make it easy to access things at addresses like R + C, where R is an address in a register and C is a relatively small integer constant. – Therefore, fixed offsets good, data-dependent offsets bad. Last modified: Mon Mar 31 10:58:48 2008 CS164: Lecture #24 1 1: No recursion, no nesting, fixed-sized data • Total amount of data is bounded, and there is only one instantiation of a function at a time. • So all variables, return addresses, and return values can go in fixed locations. • No stack needed at all. • Characterized FORTRAN programs in the early days. • In fact, can dispense with call instructions altogether: expand func- tion calls in-line. E.g., def f (x): x *= 42 x_1 = 3 y=9+x; =⇒ =⇒ x_1 *= 42 g (x, y) becomes y_1 = 9 + x_1 g (x_1, y_1) f (3) • However, program may get bigger than you want. Typically, one in- lines only small, frequently executed functions. Last modified: Mon Mar 31 10:58:48 2008 CS164: Lecture #24 2 2: Add recursion Top of stack f’s • Now, total amount of data is un- locals fixed distance bounded, and several instantiations of ra Base of a function can be active simultaneously.
    [Show full text]