Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Modern JavaScript Workflow Explained For Dinosaurs

0

Category : , , ,

Great article on the "most common" workflow used by front end developers and a brief overview of the tools used.
https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70


JavaScript package managers(npm)

Bower was arguably the most popular in 2013, but eventually was overtaken by npm around 2015. (It’s worth noting that starting around late 2016, yarn has picked up a lot of traction as an alternative to npm’s interface, but it still uses npm packages under the hood.)

JavaScript module bundler (webpack)

In 2009, a project named CommonJS was started with the goal of specifying an ecosystem for JavaScript outside the browser. A big part of CommonJS was its specification for modules, which would finally allow JavaScript to import and export code across files like most programming languages, without resorting to global variables. The most well-known of implementation of CommonJS modules is node.js. As mentioned earlier, node.js is a JavaScript runtime designed to run on the server.

The most popular module bundler was Browserify, which was released in 2011 and pioneered the usage of node.js style require statements on the frontend (which is essentially what enabled npm to become the frontend package manager of choice). Around 2015, webpack eventually became the more widely used module bundler (fueled by the popularity of the React frontend framework, which took full advantage of webpack’s various features).

Transpiling code for new language features (babel)

Transpiling code means converting the code in one language to code in another similar language. This is an important part of frontend development — since browsers are slow to add new features, new languages were created with experimental features that transpile to browser compatible languages.

For CSS, there’s Sass, Less, and Stylus, to name a few. For JavaScript, the most popular transpiler for a while was CoffeeScript (released around 2010), whereas nowadays most people use babel or TypeScript. CoffeeScript is a language focused on improving JavaScript by significantly changing the language — optional parentheses, significant whitespace, etc. Babel is not a new language but a transpiler that transpiles next generation JavaScript with features not yet available to all browsers (ES2015 and beyond) to older more compatible JavaScript (ES5). Typescript is a language that is essentially identical to next generation JavaScript, but also adds optional static typing. Many people choose to use babel because it’s closest to vanilla JavaScript.

Using a task runner (npm scripts)

Now that we’re invested in using a build step to work with JavaScript modules, it makes sense to use a task runner, which is a tool that automates different parts of the build process. For frontend development, tasks include minifying code, optimizing images, running tests, etc.

In 2013, Grunt was the most popular frontend task runner, with Gulp following shortly after. Both rely on plugins that wrap other command line tools. Nowadays the most popular choice seems to be using the scripting capabilities built into the npm package manager itself, which doesn’t use plugins but instead works with other command line tools directly.

Knockout JS Intro

0

Category : ,

Introduction

Knockout is a fast, extensible and simple JavaScript library designed to work with HTML document elements using a clean underlying view model. It helps to create rich and responsive user interfaces. Any section of UI that should update dynamically (e.g., changing depending on the user’s actions or when an external data source changes) with Knockout can be handled more simply and in a maintainable fashion.

Working with Knockout consists of several steps:

  • Get data model:
    In most cases, data will be returned from the remote server in JSON format with AJAX (Asynchronous JavaScript and XML) call.

  • Create View:
    View is a HTML template with Knockout bindings, using “data-bind” attributes. It can contain grids, divs, links, forms, buttons, images and other HTML elements for displaying and editing data.

  • Create View Model:
    View model is a pure-code representation of the data operations on a UI. It can have usual properties and observable properties. An observable property means that when it’s changed in the view model, it will automatically be updated in the UI.

  • Map data from data model to view model:
    In most cases, data in the data model are independent from UI and don’t have a concept of observables. In this step a map from the data model to the view model should be created. It can be done manually or using Knockout mapping plugin.

  • Bind view model to the view:
    When view model is initialized, it can be bound to part of the HTML document, or the whole HTML document.

Data-Bind

An HTML attribute data-bind is used to bind a view model to the view. It is a custom Knockout attribute and is reserved for Knockout bindings. The data-bind attribute value consists of two parts: name and value, separated by a colon. Multiple bindings are separated by a comma.

The binding item name should match a built-in or custom binding handler. The binding item value can be a view model property or any valid JavaScript expression or any valid JavaScript variable:
File Name



Live Examples

http://knockoutjs.com/examples/
http://www.knockmeout.net/2011/08/all-of-knockoutjscom-live-samples-in.html

Tutorials

http://learn.knockoutjs.com/

Documentation

http://knockoutjs.com/documentation/introduction.html

my thanks to the below tutorials/blogs:
https://www.devbridge.com/articles/knockout-a-real-world-example
http://www.knockmeout.net/2011/08/all-of-knockoutjscom-live-samples-in.html

Asynchronous requests with Postman's PM API

0

Category : , , ,

You can send requests asynchronously with the pm API method sendRequest, these can be used in the pre-request or the test script.

Its important to note that if you send an asynch request in the pre-request tab "The main Postman request will NOT be sent until the pre-request script is determined to be finished with all callbacks, including sendRequest."

A blog post containing more detailed info on this can be seen on the below link:
http://blog.getpostman.com/2017/10/03/send-asynchronous-requests-with-postmans-pm-api/

I have only done basic testing with this but I could get the method to fire using the 2nd example of the 3 available on the previous url:
var headers = ['reseller_id:' + environment.booking_api_reseller_id];
    headers.push('request_id:'+ environment.booking_api_request_id);
    headers.push('request_authentication:'+ environment.booking_api_request_authentication);
console.log(headers);

// Example with a full fledged SDK Request
const echoPostRequest = {
  url: environment.booking_api_host + '/v1/Availability/product/' + environment.booking_api_availability_productKey + '?fromDateTime=' + environment.booking_api_availability_start_date + 
        '&toDateTime=' + environment.booking_api_availability_end_date,
  method: 'GET',
  header: headers,
  body: {
    mode: 'raw',
    raw: JSON.stringify({ key: 'this is json' })
  }
};

pm.sendRequest(echoPostRequest, function (err, res) {
    console.log('..............here........');
    console.log(err ? err : res.json());
});

I was having issues passing the headers to the request but i found the below url which states the header param should be an array.
http://www.postmanlabs.com/postman-collection/Request.html#~definition

Reuseable scripts in Postman

0

Category : , , ,

You can reuse methods across requests in postman.

Tip #5 in the below list:
http://blog.getpostman.com/2017/07/28/api-testing-tips-from-a-postman-professional/

  1. Init in Pre-Request or Tests tab or in a previous request.
  2. Store in an Environment or Global variable.
  3. Then call multiple times from other requests.
1) Setup method in Pre-Request or Tests tab in Postman, you can also list params to pass to method.
postman.setEnvironmentVariable("commonTests", (responseBody, environmentSchema) => {
    
    // parse response and log
    var responseObject = JSON.parse(responseBody);
    //console.log("response: " + JSON.stringify(responseObject));

    // test to check status code
    tests["Status code is 200"] = responseCode.code === 200;
    
    // test response time
    console.log("responseTime: " + responseTime);
    tests["Response time is less than " + environment.max_server_response_time + "ms"] = responseTime < environment.max_server_response_time;
    
    // validate schema
    eval(environment.validateSchema)(responseObject, environmentSchema);
});

2) Call method from the Pre-Request or Tests tab in Postman.
You can also call methods from within another method as you can see at the end of the previous code sample.

    // validate schema
    eval(environment.commonTests)(responseObject, environment.specificSchema);

Modern Javascript Learning Path

0

Category :

When you’re learning any new language, you write code and then you throw it away, and then you write some more. My modern JavaScript education has been a stepladder of tutorials, then a small tractable project during which I compiled a list of questions and problems, then a check-in with my coworkers to get answers and explanations, then more tutorials, then a slightly bigger project, more questions, a check-in — wash, rinse, repeat.

Here’s an incomplete list of some of the workshops and tutorials I’ve run through in this process so far.

  • 1) HOW-TO-NPM — npm is the package manager for JavaScript. Even though I’d typed npm install thousands of times before I started this process, I didn’t know all the things npm does till I completed this interactive workshop. (On several projects I’ve since moved onto using yarn instead of npm, but all the concepts translate.)
  • 2) learnyounode — I decided to focus on server-side JavaScript first because that’s where I’m comfortable, so Node.js it is. Learnyounode is an interactive introduction to Node.js similar in structure to how-to-npm.
  • 3) expressworks — Similar to the previous two workshoppers, Expressworks is an introduction to Express.js, a web framework for Node.js. Express doesn’t get a whole lot of use here at Postlight these days, but it was worth learning as a beginner to get a taste of building a simple webapp.
  • 4) Now it was time to build something real. I found Tomomi Imura’s tutorial on Creating a Slack Command Bot from Scratch with Node.js was just enough Node and Express to put my newfound skills to work. Since I was focusing on backend, building a slash command for Slack was a good place to start because there’s no frontend presentation (Slack does that for you).

    5) In the process of building this command, instead of using ngrok or Heroku as recommended in the walkthrough, I experimented with Zeit Now, which is an invaluable tool for anyone building quick, one-off JS apps.

    6) Once I started writing Actual Code, I also started to fall down the tooling rabbit hole. Installing Sublime plugins, getting Node versioning right, setting up ESLint using Airbnb’s style guide (Postlight’s preference) — these things slowed me down, but also were worth the initial investment. I’m still in the thick of this; for example, Webpack is still pretty mysterious to me, but this video is a pretty great introduction.

    7) At some point JS’s asynchronous execution (specifically, “callback hell”) started to bite me. Promise It Won’t Hurt is another workshopper that teaches you how to write “clean” asynchronous code using Promises, a relatively new JS abstraction for dealing with async execution. Truth be told, Promises almost broke me — they’re a mind-bendy paradigm shift. Thanks to Mariko Kosaka, now I think about them whenever I order a burger.

    8) From here I knew enough to get myself into all sorts of trouble, like experiment with Jest for testing, Botkit for more Slack bot fun, and Serverless to really hammer home the value of functional programming. If you don’t know what any of that means, that’s okay. It’s a big world, and we all take our own paths through it.

    my thanks to this great post:
    https://trackchanges.postlight.com/modern-javascript-for-ancient-web-developers-58e7cae050f9

    AngularJS Basics

    0

    Category :

    1) Angular Directive = ng-app

    2) Access Angular Model through controllers

    3) $scope is Angular Model

    4) ng-controller directive sets js function name to use as controller for a portion of page, different portions of the page could have diff controllers.

    5) Setting ng-app="nameApp" prevents polluting of the global namespace:
     
     <html ng-app="nameApp">
       <head>
         <meta charset="utf-8">
         <title>Angular.js Example</title>
         <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
         <script>
           var nameApp = angular.module('nameApp', []);
           nameApp.controller('NameCtrl', function ($scope){
             $scope.firstName = 'John';
             $scope.lastName = 'Smith';
           });
         </script>
       </head>
       <body ng-controller="NameCtrl">
         First name:<input ng-model="firstName" type="text"/>
         <br>
         Last name:<input ng-model="lastName" type="text"/>
         <br>
         Hello {{firstName}} {{lastName}}
       </body>
         </html>
        
    
    6) Could have multiple Angular apps running on the same page.







    my thanks to:
    https://github.com/curran/screencasts/tree/gh-pages/introToAngular

    AngularJS Intro

    3

    Category :

    Data Binding Framework

    Main usage creating single-page apps.
    Based on MVC architecture

    Provide solutions for:

  • Routing - handling updates to the url hash fragment
  • Templating - dynamically creating and updating HTML based on templates and models
  • Data binding - synchronise the model and user interface
  • Top data-binding frameworks:

    AngularJS
    KnockoutJS
    Ember
    JsViews

    Related libraries

    • jQuery - industry standard library for DOM manipulation and AJAX
    • AMD - for seperating JavaScrip projects across many files using modules, allowing depencies from one files on another. Require
    • Angular provides a jQuery like API jqLite - which is like jQuery minimal functionality
    • Promises - industry standard pattern for dealing with asynchronous control flow. The top Promises implementation is Q.
    • Async.js
    • Handlebars - templating engine. Angular Templates use similar syntax.

    Angular Learning Resources

    It is straightforward to teach yourself about Angular, as there are so many learning resources on the Web.

    Bird's-eye-view:

    Learn Angularjs This Weekend - Advice on which resources to use for getting up to speed on Angular.
    A Better Way to Learn AngularJS - A great collection of links to resources for learning Angular.
    AngularJS-Learning - A kitchen sink of links to Angular learning resources.

    Introductory tutorials and guides:

    Angular Developer Guide Conceptual Overview
    • Enumerates fundamental concepts
    • Provides several code examples
    Official Angular Tutorial
    • Useful to read through
    • Emphasizes testing
    • Starts with complex boilerplate project
    • Great diagrams
    Egghead.io
    • A collection of short screencasts (scroll to the bottom for intoduction content)
    AngularJS Fundamentals In 60-ish Minutes
    • A talk on YouTube that covers fundamentals of Angular
    Learn Angular.js in 30 Min
    • A screencast showing how to build an app using UI-Router
    • Does not cover basics, jumps to advanced usage
    • Great example of how development flows in practice
    An Introduction to AngularJS Forms Validation

    Design and implementation of Angular:

    Re-Imagining the Browser with AngularJS
    • Talk by Miško Hevery, creator of Angular
    • Discusses the high-level goals of Angular
    Bringing Angular Apps to Life with Animation by Miško Hevery
    Google I/O 2013 - Design Decisions in AngularJS
    "Writing Directives" talk by Misko Hevery




    my thanks to: https://www.youtube.com/watch?v=TRrL5j3MIvo
    https://github.com/curran/screencasts/tree/gh-pages/introToAngular

    Moment.js

    0

    Category :

    A javascript date library for parsing, validating, manipulating, and formatting dates.

    Format Date
    moment(tourDate).format('DD/MM/YYYY')

    Format Todays Date
    moment().format("DD/MM/YYYY");

    http://momentjs.com/

    A Baseline for Front-End Developers

    0

    Category :

    Exactly as it says on the tin, a good list of what you need to know to consider yourself a half way decent "Front-End Developer"....
    http://rmurphey.com/blog/2012/04/12/a-baseline-for-front-end-developers/

    jQuery Promises

    0

    Category :

    Very good intro here: http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/

    Less.org

    0

    Category : ,

    Introduced to http://lesscss.org/ by
    http://net.tutsplus.com/tutorials/html-css-techniques/build-a-twitter-clone-from-scratch-the-design/

    Link to less js file and my local style file.
        
        
        
    

    Build up nesting of styles using Less.
    header {
     background: url(gfx/bg-header.png);
     height: 85px;
     width: 100%;
     div.wrapper {
      padding: 11px 0;
      img {
       position: relative;
       top: 10px;
       margin: 0 15px 0 0;
      }
      span {
       font-size: 18px;
       margin: 0 42px 0 0;
      }
      form {
       display: inline;
       input {
        margin: 0 0 0 14px;
       }
      }
      #btnLogOut {
       float: right;
       margin: 14px 0 0 0;
      }
     }
    }
    

    Online compiler http://winless.org/online-less-compiler to generate css from less file.

    jQuery DataTables

    0

    Category :

    Basic Implementation

    Download files from www.datatables.net
    Add files to project.
    Reference files in master/main page or on specific view.
    
    
    
    
    
    

    Initialise table as dataTable.
    
    

    Also had to add this piece of css to ensure header and footer covered all buttons within.
    div.ui-widget-header {
        height: 25px;
    }
    

    And that should be about it.

    Javascript Functions v Methods

    0

    Category :

    Functions

    A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

    All data that is passed to a function is explicitly passed.


    Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.


    Methods

    A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

    1. It is implicitly passed the object for which it was called
    2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)


    A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".

    The way objects have to expose their behavior are called methods. Methods thus are the artifact object have to "do" something.

    In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.

    Functional vs. Object-Oriented JavaScript Development

    0

    Category :

    JavaScript is such a flexible language that it can be used to write code that follows two radically different programming paradigms—functional programming and object-oriented programming (OOP).

    Natively, the JavaScript language allows you to treat functions in just the same fashion as values. You can assign a function to a variable and also pass it around to other functions. Abstractly speaking, we can say that a JavaScript function is a value of a very special type: the value is the behavior provided and the type is something we can just call “function.”

    Natively, the JavaScript language also offers objects. In JavaScript, objects are seen as plain bags of properties and methods. They look more like simple dictionaries of data and behavior than fully-fledged objects as you will find in a qualified OOP language such as C#, Java, or C++. In classic OOP, a class represents the layout of what will actually become an object once an instance of that class is created through the new operator. In JavaScript, you have no classes that provide the blueprints for objects to create. In JavaScript, the “blueprint” for an object is an implicit concept and it looks a lot like a dictionary. So in JavaScript, you just create objects and store data into them. JavaScript objects, however, offer some degree of object-oriented capabilities such as encapsulation and inheritance.

    For once, the quick answer to the question that this article addresses is not the classic “It depends.” It is, instead, a less compromising “whatever you ultimately like most”. But let’s elaborate a bit on it.

    Functional Programming in Brief

    In functional programming the building block of code is the “function”, as opposed to the class in object-oriented programming and the subroutine in procedural programming. A function is a unit of code that only describes the operations to be performed on the input. A function gets some input and returns some output; everything else is hidden from view.

    As a functional programmer, you build your applications by pipelining function calls to create a super function that just gets the program’s input and returns the program’s output. There’s typically no layer where you process the input, store state, arrange a sequence of statements, update the state, and decide about the next step. A function is a like a value and can be used as an argument and be passed to other functions as well as used in any other context where values can be used.

    Note, though, that real-world functional languages such as F# also mix concepts like functions and pipelining with variables and some simple notion of state. F#, for example, lets you store intermediate results in some local variable and use it as the input for successive function calls. The scope of such variables though is fairly limited and there’s anything like global or static members.

    JavaScript and Functional Programming

    JavaScript is not a truly functional language such as F#. JavaScript, however, does support some constructs that are typical of a functional language. By using these constructs extensively, you can do good functional programming in JavaScript. At the end of the day, this is largely what you do when you use the jQuery library.

    In JavaScript, anonymous functions are the pillar of functional programming. An anonymous function is a direct offshoot of lambda calculus or, if you like it most, a language adaptation of old-fashioned function pointers.

    The only difference between a regular function and an anonymous function is in the name. In a functional context, you don’t strictly need to name a function especially if you’re using it as a value that you pass around. Here’s an example that shows how to combine together various functions.

    // Function to calculate a total
    var CalcTotal = function(x, y) {
       return x + y;
    };
     
    // Function to add taxes
    var AddTaxes = function(x) {
      return x * 1.2;
    };
     
    // Function that pipelines the other two
    var CalcTotalPlusTaxes = function (fnCalcTotal, fnAddTaxes, x, y) {
        return fnAddTaxes(fnCalcTotal(x, y)); 
    };
     
    // Execution
    var result = CalcTotalPlusTaxes(CalcTotal, AddTaxes, 40, 60);
    alert(result);
    

    Treating anonymous functions as plain values allows you to mix data and behavior in a quite effective way. This gives you a chance to apply some design principles to JavaScript code such as Dependency Inversion. When a higher level module (whether an object or a function) depends on capabilities provided by lower level modules, you can just inject the expected behavior as an argument. In many cases, this approach augments the readability and elegance of the code; for sure, it gives you more power to deal with complexity.

    jQuery and the Consecration of Functional Programming

    The jQuery library called more than ever the people’s attention on functional programming. The jQuery library is based on the jquery object or $. The $ is essentially a wrapper around DOM elements and DOM elements can be passed into the object through the type constructor—the popular $(…) expression. Furthermore, jQuery allows call chaining meaning that the $ object can pass its own wrapped values into other functions that return the same $ object.

    These three facts about jQuery qualify the root object of the library as a monad; and monads are a fundamental concept in the theory of functional languages. jQuery takes you to reason in terms of chunks of behavior that you concatenate and pass around. This is extremely effective as long as the values you ultimately work with are just those that library manipulates natively. The jQuery library is effective because it allows you to enjoy the power (and to some extent the cleanness) of functional programming for the Web environment where all you do is manipulation of wrapped DOM elements.

    You may be a huge fan of the jQuery library and appreciate the functional lifestyle it pushes. However, that has to be put into perspective and should not become a reason to push the functional programming paradigm over everything else. Let’s have a look at the following snippet from the source code of jQuery.

    jQuery.fn = jQuery.prototype = {
        init: function( selector, context ) { ... },
           size: function() { return this.length; },
           each: function( callback, args ) {
            return jQuery.each( this, callback, args );  },
           ready: function( fn ) { ... }
           :
    }
    

    As you can see, the jQuery object has its own prototype featuring capabilities such as size and each. More interestingly, when you write a jQuery plugin you just extend the basic prototype adding a new function. At the end of the day, effective JavaScript programming is always a mix of functional and object-oriented style. With jQuery, though, you are mostly exposed to the functional part of it.

    Objects in JavaScript

    There’s a significant difference between objects in a qualified OOP language and JavaScript. In OOP languages, the class is a blueprint for actual objects you use. In JavaScript, you just have objects whose blueprint is that of a dictionary of data and functions. When you create a new object in JavaScript, you have an empty dictionary you can fill with anything you like.

    Having said that, with a bit of work you can create (and reuse) custom objects and manage for them to inherit from existing objects and also behave polymorphically. This work is just what JavaScript object-oriented libraries do.

    When it comes to adding layers to JavaScript to make it closer to a qualified OOP language and gain some more programming power and code reusability, you have to choose from two main approaches for extending the capabilities of the native JavaScript objects: closures and prototypes.

    Before we get to that, however, a few words about the native Object type in JavaScript and it usage.

    You can use the new keyword to create a new dictionary-like object in JavaScript. Next, you stuff data into it and you can add methods by wiring functions to property names. Here’s an example:

    var person = new Object();
     person.Name = "Dino";
     person.LastName = "Esposito";
     person.BirthDate = new Date(1979,10,17)
     person.getAge = function() {
     var today = new Date();
     var thisDay = today.getDate();
     var thisMonth = today.getMonth();
     var thisYear = today.getFullYear();
     var age = thisYear-this.BirthDate.getFullYear()-1;
     if (thisMonth > this.BirthDate.getMonth())
       age = age +1;
     else 
     if (thisMonth == this.BirthDate.getMonth() &&
       thisDay >= this.BirthDate.getDate())
       age = age +1;
     return age;
    }
    

    What we have is an object modeled after a person; we don’t have a Person object. A possible way to define the layout of a type is creating a new, all-encompassing function that exposes just the members we like. In addition, in JavaScript all intrinsic objects have a read-only property named prototype. You can use the prototype property to provide a base set of functionality shared by any new instance of an object of that type. These two are the mechanisms to leverage for OOP in JavaScript.

    Object-orientation through Closures

    A closure is a general concept of programming languages. Applied to JavaScript, a closure is a function that can have variables and methods defined together within the same context. In this way, the outermost (anonymous or named) function “closes” the expression. Here’s an example of the closure model for a function that represents a Person type:

    var Person = function(name, lastname, birthdate) 
    {
       this.Name = name;
       this.LastName = lastname;
       this.BirthDate = birthdate;
     
       this.getAge = function() {
          var today = new Date();
          var thisDay = today.getDate();
          var thisMonth = today.getMonth();
          var thisYear = today.getFullYear();
          var age = thisYear-this.BirthDate.getFullYear()-1;
          if (thisMonth > this.BirthDate.getMonth())
              age = age +1;
          else 
             if (thisMonth == this.BirthDate.getMonth() &&
                 thisDay >= this.BirthDate.getDate())
                 age = age +1;
          return age;
       }
    }
    

    As you can see, the closure is nothing more than the constructor of the pseudo-class. In a closure model, the constructor contains the member declarations and members are truly encapsulated and private to the class. In addition, members are instance based, which increases the memory used by the class. Here’s how you use the object:

    var p = new Person("Dino", "Esposito", new Date( ... );
    alert(p.Name + " is " + p.getAge());
    

    The closure model gives full encapsulation, but nothing more. To compose objects, you can only resort to aggregation.

    Object-orientation through Prototypes

    The prototype model entails that you define the public structure of the class through the JavaScript prototype object. The following code sample shows how to rewrite the preceding Person class to avoid a closure.

    // Pseudo constructor
    var Person = function(name, lastname, birthdate)
    {
      if(name && lastname && birthdate) {
       this.initialize(name, lastname, birthdate);
      }
    }
    // Members
    Person.prototype.initialize = function(name, lastname, birthdate)
    {
    
     this.Name = name;
     this.LastName = lastname;
     this.BirthDate = birthdate;
    }
    
    Person.prototype.getAge = function()   
    {
     var today = new Date();
     var thisDay = today.getDate();
     var thisMonth = today.getMonth();
     var thisYear = today.getFullYear();
     var age = thisYear-this.BirthDate.getFullYear()-1;
     if (thisMonth > this.BirthDate.getMonth())
      age = age +1;
     else 
        if (thisMonth == this.BirthDate.getMonth() &&
         thisDay >= this.BirthDate.getDate())
         age = age +1;
     return age;
    }
    

    In the prototype model, the constructor and members are clearly separated and a constructor is always required. As for private members, you just don’t have them. The var keyword which would keep them local in a closure doesn’t apply in the prototype model. So you can define getter/setter for what you intend to be properties, but the backing field will anyway remain accessible from the outside. You can resort to some internal (and documented) convention such as prefixing with an underscore the name of members you intend as private. It’s just a convention, however.

    By using the prototype feature you can achieve inheritance by simply setting the prototype of a derived object to an instance of the “parent” object.

    Developer = function Developer(name, lastname, birthdate) 
    { 
       this.initialize(name, lastname, birthdate);
    }
    Developer.prototype = new Person();
    

    Note that you always need to use this to refer to members of the prototype from within any related member function.

    Closure vs. Prototype

    In the prototype model, members are shared by all instances as they are invoked on the shared prototype object. In this way, the amount of memory used by each instance is reduced which would also provide for faster object instantiation. Aside from syntax peculiarities, the prototype model makes defining classes much more similar to the classic OOP model than the closure model.

    The choice between closure and prototype should also be guided by performance considerations and browser capabilities. Prototypes have a good load time in all browsers; and indeed, they have excellent performance in Firefox. (In contrast, closures have a better load time than prototypes in Internet Explorer.) Prototypes provide better support for IntelliSense, and allow for tool-based statement completion when used in tools that support this feature, such as Visual Studio. Prototypes can also help you obtain type information by simply using reflection. You won’t have to create an instance of the type in order to query for type information, which is unavoidable if closures are used. Finally, prototypes allow you to easily view private class members when debugging. Debugging objects derived using the closure model requires a number of additional steps.

    As an example, consider that the Microsoft AJAX library is built using the prototype model (and the closure model was discarded along the way).


    Conclusion

    JavaScript is neither 100% functional or object-oriented. However, it lends itself to support to a good extent both paradigms, because in a way it borrows concepts from both qualified functional and object-oriented languages. This inevitably creates some noise around the programming techniques you can employ. As a developer, you must be ready to accept compromises that may not be acceptable in a fully-qualified functional or object-oriented scenario.

    JavaScript is a must today for writing client-side code for Web and mobile applications. And the client-side code we are called to write is no longer plain scripting of the document object model as it was when the language was introduced. Today, we often use JavaScript for some client-side logic and input validation. To make the whole development process more sustainable, we resort to JavaScript libraries that abstract through functions or classes some of the most common tasks. The jQuery library is just the most illustrious example.

    Because of the success of the jQuery library, functional programming is probably gaining momentum and overcoming object-oriented programming in JavaScript. But in the end, the final decision is left to you and attitude, skills, and ease are the key parameters for a decision. You don’t have to take it as a matter of religion and pick up option and stick to that forever. To use JavaScript at its best, you probably have to mix functional features with OO features.

    Having said that, if I have to write client code for a Web front-end, I’d probably go with jQuery, use a lot of anonymous functions and don’t even bother about custom objects. Instead, if I have to write my own framework to support some server-side infrastructure, well, I’d probably opt for an object-oriented approach and consider closures or prototypes.

    my thanks to:
    http://msdn.microsoft.com/en-us/scriptjunkie/gg476048.aspx

    JavaScript Module Pattern: In-Depth

    0

    Category :

    The module pattern is a common JavaScript coding pattern. It's generally well understood, but there are a number of advanced uses that have not gotten a lot of attention.

    The Basics

    We'll start out with a simple overview of the module pattern

    Anonymous Closures

    This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We'll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

    (function () { 
        // ... all vars and functions are in this scope only 
        // still maintains access to all globals 
    }());
    

    Notice the () around the anonymous function. This is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead.

    Global Import

    JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it's used in an assignment, the global is created if it doesn't already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it's not obvious (to humans) which variables are global in a given file.

    Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

    (function ($, YAHOO) { 
        // now have access to globals jQuery (as $) and YAHOO in this code 
    }(jQuery, YAHOO));
    

    Module Export

    Sometimes you don't just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function's return value. Doing so will complete the basic module pattern, so here's a complete example:

    var MODULE = (function () { 
        var my = {}, 
            privateVariable = 1; 
         
        function privateMethod() { 
            // ... 
        } 
         
        my.moduleProperty = 1; 
        my.moduleMethod = function () { 
            // ... 
        }; 
         
        return my; 
    }());
    

    Notice that we've declared a global module named MODULE, with two public properties: a method named MODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal state using the closure of the anonymous function.

    Advanced Patterns

    While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.

    Augmentation

    One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:

    var MODULE = (function (my) { 
        my.anotherMethod = function () { 
            // added method... 
        }; 
     
        return my; 
    }(MODULE));
    

    After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.

    Loose Augmentation

    While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn't always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:

    var MODULE = (function (my) { 
        // add capabilities... 
         
        return my; 
    }(MODULE || {}));
    

    In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.

    Tight Augmentation

    While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):

    var MODULE = (function (my) { 
        var old_moduleMethod = my.moduleMethod; 
         
        my.moduleMethod = function () { 
            // method override, has access to old through old_moduleMethod... 
        }; 
         
        return my; 
    }(MODULE));
    

    Here we've overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

    Cloning and Inheritance


    var MODULE_TWO = (function (old) { 
        var my = {}, 
            key; 
         
        for (key in old) { 
            if (old.hasOwnProperty(key)) { 
                my[key] = old[key]; 
            } 
        } 
         
        var super_moduleMethod = old.moduleMethod; 
        my.moduleMethod = function () { 
            // override method on the clone, access to super through super_moduleMethod 
        }; 
         
        return my; 
    }(MODULE));
    

    This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I've written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I've included it for completeness.

    Cross-File Private State

    One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will maintain private state across all augmentations:

    var MODULE = (function (my) { 
        var _private = my._private = my._private || {}, 
            _seal = my._seal = my._seal || function () { 
                delete my._private; 
                delete my._seal; 
                delete my._unseal; 
            }, 
            _unseal = my._unseal = my._unseal || function () { 
                my._private = _private; 
                my._seal = _seal; 
                my._unseal = _unseal; 
            }; 
         
        // permanent access to _private, _seal, and _unseal 
         
        return my; 
    }(MODULE || {}));
    

    Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application's lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed.

    Sub-modules

    Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:

    MODULE.sub = (function () { 
        var my = {}; 
        // ... 
         
        return my; 
    }());
    

    Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.

    Conclusions

    Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I'd combine loose augmentation, private state, and sub-modules.

    I haven't touched on performance here at all, but I'd like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.

    To close, here's an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I've left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.

    var UTIL = (function (parent, $) { 
        var my = parent.ajax = parent.ajax || {}; 
         
        my.get = function (url, params, callback) { 
            // ok, so I'm cheating a bit :) 
            return $.getJSON(url, params, callback); 
        }; 
         
        // etc... 
         
        return parent; 
    }(UTIL || {}, jQuery));
    

    my thanks to:
    http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

    Javascript Closures

    0

    Category :

    Douglas Crockford’s five part series on Javascript

    Crockford shows a much nicer object creation strategy based on closures, which looks something like this:

    var animalsApp = (function(){
    
        var new_animal = function(name) {
            var animal = {};
    
            animal.sayHello = function() {
                return "Hello, my name is " + name;
            }
            return animal;
        }
    
        var new_dog = function(name) {
            var dog = new_animal(name);
    
            dog.bark = function() {
                return "woof";
            }
            return dog;
        }
    
        var new_cat = function(name) {
            var cat = new_animal(name);
    
            cat.meow = function() {
                return "eeooowww";
            }
            return cat;
        }
    
        return {
            main: function(){
                var dog = new_dog("rover");
    
                console.log(dog.sayHello());
                console.log(dog.bark());
    
                var cat = new_cat("tom");
    
                console.log(cat.sayHello());
                console.log(cat.meow());
            }
        };
    }());
    
    animalsApp.main();
    

    Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).


    my thanks to:
    http://mikehadlow.blogspot.com/2010/12/javascript-defining-classes-with.html

    Javascript Functions

    0

    Category :

    Functions in JavaScript let you define code that is called on demand, instead of immediately. There are several ways to define a function:

    Function Declaration

    standard function statement
    • must always have an Identifier(function name).
    • parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated before any other expressions contained in a scope.

    function getarea(w,h){
     //standard function
     return w * h;
    }
    
    getarea(3,5) //calls function
    

    Function Literal or Expression

    an anonymous function assigned to a variable
    var getarea = function(w,h){
     return w * h;
    }
    
    getarea(3,5) //calls function
    

    Function Expression may omit Identifier.
    Named Function Expressions may only access its Identifier in the scope of its newly-defined function
    Named Function Expressions make for a much more pleasant debugging experience.

    Function Constructor

    creates a function on the fly, which is slower and generally discouraged
    //syntax: new Function(argument1, argument2, ..., argumentY, functionbody) 
    //all parameters must be a string
    
    var getarea=new Function("w", "h", "var area=w*h; return area")
    getarea(3,5) //calls function
    



    What's the difference between declaration and expression?

    The 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
    This means following is valid.
    var sum = function mySum(a, b) { return a + b; }
    
    Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
    var test1 = function test2() { alert(typeof test2); }
    
    alert(typeof(test2)); //alerts 'undefined', surprise! 
    
    test1(); //alerts 'function' because test2 is a function.
    

    ECMAScript differentiates between two based on a context. If a function foo(){} is part of, say, assignment expression, it is considered a function expression. If, on the other hand, function foo(){} is contained in a function body or in a (top level of) program itself — it is parsed as a function declaration.

    // declaration, since it's part of a Program
    function foo(){};
    
    // expression, since it's part of an AssignmentExpression
    var bar = function foo(){};
    
    // expression, since it's part of a NewExpression
    new function bar(){};
    
    (function(){
      function bar(){} // declaration, since it's part of a FunctionBody
    })();
    

    A somewhat less obvious example of function expression is the one where function is wrapped with parenthesis — (function foo(){}). The reason it is an expression is again due to a context: "(" and ")" constitute a grouping operator and grouping operator can only contain an expression

    function foo(){} // function declaration
    (function foo(){}); // function expression: due to grouping operator
      
    try {
      // grouping operator can only contain expression, 
      //not a statement (which `var` is)
      (var x = 5); 
    } catch(err) {
      // SyntaxError
    }
    

    Immediately-Invoked Function Expression (IIFE)

    The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

    // Either of the following two patterns can be used to immediately invoke
    // a function expression, thus creating an anonymous closure with privacy.
    
    (function(){ /* code */ })(); // I've been using this one
    (function(){ /* code */ }()); // Crockford recommends this one
    
    // Because the point of the parens or coercing operators is to disambiguate
    // between function expressions and function declarations, they can be
    // omitted when the parser already expects an expression (but please see the
    // "important note" below).
    
    

    In cases where the extra “disambiguation” parens surrounding the function expression are unnecessary (because the parser already expects an expression), it’s still a good idea to use them when making an assignment, as a matter of convention. Such parens typically indicate that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself.

    Properties

    arguments

    A local variable that points to the "arguments" object, which contains all of the arguments passed into the function. Use "arguments.length" to determine the number of arguments entered. You can use this property to define functions that accept varying number of parameters.

    caller

    References the function in which the current function is called inside of. If the current function is called at the top level, caller returns null. You can use this property to check the context in which a function is being called.

    function myresidence(){
     calltest()
    }
    
    // alerts function myresidence(), 
    // the function in which calltest() was called inside
    myresidence() 

    prototype

    Lets you add custom properties and methods to a function's prototype object, which instantly adds them to all instances of the function initialized using the new operator (also called a constructor function). In the below, I'm adding a getprice() method to the constructor function Car() that is reflected on all instances of new Car():

    function Car(baseprice, years_old){
     this.baseprice=baseprice
     this.history=years_old
    }
    
    //add method getprice() to all instances of Car (called using new Car())
    Car.prototype.getprice=function(){
     this.price=this.baseprice - (this.history * 1000)
     alert(this.price)
    }
    
    var mytoyota=new Car(20000, 10)
    mytoyota.getprice() //alerts 10,000
    
    var myford=new Car(18000, 5)
    myford.getprice() //alerts 13,000

    You can also use the prototype object to extend prebuilt JavaScript objects that are initialized using the new operator with custom methods, such as with Date(), Array(), or String(). Lets extend the default String object with a backwards() method that takes a string and returns it backwards (ie: "george" becomes "egroeg"):

    String.prototype.backwards=function(){
     var strlen=this.length, reversestr=''
     //loop through each char within string backwards
     for (var i=strlen-1; i>-1; i--) 
      reversestr+=this.charAt(i)
     return reversestr
    }
    
    document.write('george'.backwards()) //writes out "egroeg"
    

    Methods

    funcA.apply(funcB, [argument1, argument2, argumentN])

    Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. Identical to call() below, except any arguments passed into funcA should be wrapped in an array.

    funcA.call(funcB, argument1, argument2, argumentN)

    Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. The two methods apply() and call() are useful when you wish an object to "borrow" a method from another object and use it within its own context.

    The following illustrates this:
    function borrowme(name){
     this.bonus=(this.salary * 0.15) + (this.seniority * 500)
     alert(name + ", your bonus for this year is: " + this.bonus)
    }
    
    function employee(seniority, salary){
     this.seniority=seniority
     this.salary=salary
    }
    
    var employee1=new employee(10, 30000) 
    //returns "Sarah, your bonus for this year is: 9500"
    borrowme.call(employee1, "Sarah") 

    Here the custom object "employee" uses the function "borrowme()" to manipulate a few numbers stored within it. Normally the keyword "this" in borrowme() references just that- the function itself. However, when it''s invoked using call(), the context of "this" changes so it references the object passed into the first parameter of call(), or in this case, "employee1".

    apply() and call() are important tools in implementing inheritance in JavaScript.

    toString()

    Returns a string that represents the source code (raw text) of the function. A useful method in debugging, by looking at the source code of a function.

    my thanks to:
    http://www.javascriptkit.com/jsref/function.shtml
    http://kangax.github.com/nfe/
    http://benalman.com/news/2010/11/immediately-invoked-function-expression/

    Common JavaScript Design Pattern - jQuery.doc.ready

    0

    Category :

    Let me show you an overview, and then look at how it comes together:

    function MyScript(){}
    (function()
    {
      var THIS = this;
      function defined(x)
      {
        return typeof x != 'undefined';
      }
      this.ready = false;
      this.init = function(
      {
        this.ready = true;
      };
      this.doSomething = function()
      {
      };   
      var options = {
          x : 123,
          y : 'abc'
          };
      this.define = function(key, value)
      {
        if(defined(options[key]))
        {
          options[key] = value;
        }
      };
    }).apply(MyScript);

    As you can see from that sample code, the overall structure is a function literal:
    (function()
    {
      ...
    })();

    A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately:

    function doSomething()
    {
      ...
    }
    
    doSomething();

    I originally started using function literals for the sake of encapsulation—any script in any format can be wrapped in that enclosure, and it effectively “seals” it into a private scope, preventing it from conflicting with other scripts in the same scope, or with data in the global scope. The bracket-pair at the very end is what executes the scope, calling it just like any other function.

    But if, instead of just calling it globally, the scope is executed using Function.apply, it can be made to execute in a specific, named scope which can then be referenced externally.

    So by combining those two together—the creation of a named function, then the execution of a function literal into the scope of the named function—we end up with a single-use object that can form the basis of any script, while simulating the kind of inheritance that’s found in an object-oriented class.

    The Beauty Within

    By wrapping it up in this way we have a construct that can be associated with any named scope. We can create multiple such constructs, and associate them all with the same scope, and then all of them will share their public data with each other.

    But at the same time as sharing public data, each can define its own private data too. Here for example, at the very top of the script:

    var THIS = this; 

    We’ve created a private variable called THIS which points to the function scope, and can be used within private functions to refer to it

    Private functions can be used to provide internal utilities:
    function defined(x)
    {
      return typeof x != 'undefined';
    }
    

    Then we can create public methods and properties, accessible to other instances, and to the outside:
    this.ready = false;
    this.init = function()
    {
      this.ready = true;
    };
    this.doSomething = function()
    {
    };

    We can also create privileged values—which are private, but publicly definable, in this case via the public define method; its arguments could be further validated according to the needs of the data:

    var options = {
      x : 123,
      y : 'abc'
      };
    this.define = function(key, value)
    {
      if(defined(options[key]))
      {
        options[key] = value;
      }
    };

    THIS or That?

    The enclosing scope of any function can be referred to as this, so when we define a named or anonymous enclosure, this refers to that enclosure at the top level; and it continues to refer to that enclosure from within its public methods.

    But within private functions, this refers to the immediate enclosing scope (the private function), not the top-level enclosing scope. So if we want to be able to refer to the top-level scope, we have to create a variable which refers to it from anywhere. That’s the purpose of "THIS":

    function MyScript(){}
    (function()
    {
       var THIS = this;  
       function defined(x)
       {
          alert(this);      //points to defined()
          alert(THIS);      //points to MyScript()
       }
    }).apply(MyScript);
    

    Wrapped Up!

    All of these features are what makes the construct so useful to me. And it’s all wrapped up in a neat, self-executing singleton —a single-use object that’s easy to refer-to and integrate, and straightforward to use!


    my thanks to:
    http://blogs.sitepoint.com/2010/11/30/my-favorite-javascript-design-pattern/
    http://blogs.sitepoint.com/2010/12/08/the-anatomy-of-a-javascript-design-pattern/

    JavaScript, 5 ways to call a function

    0

    Category :

    JavaScript has functional programming characteristics, and that can get in our way until we decide to face and learn it.
    Let's first create a simple function that we will be using through the rest of this post. This function will just return an array with the current value of this and the two supplied arguments.

    
    

    1) Most common way, unfortunately, global function calls

    When we are learning JavaScript we learn how to define functions using the syntax used in the example above. We learn that it's also very easy to call that function — all we need to do is:

    makeArray('one', 'two');  
       // => [ window, 'one', 'two' ]  
    

    That makeArray function isn't just a loose "global" function, it's a method of the global object. Bringing ourselves back to the browser, the global object is mapped to the window object in this environment.

    I say it's unfortunate that this is the most common way because it leads us to declare our functions globally by default. And we all know that global members are not exactly the best practice in software programming. This is especially true in JavaScript. Avoid globals in JavaScript, you won't regret it.

    JavaScript function invocation rule #1
    In a function called directly without an explicit owner object, like myFunction(), causes the value of this to be the default object (window in the browser).

    2) Method call

    Let's now create a small object and use the makeArray function as one of its methods. We will declare the object using the literal notation. Let's also call this method.

    //creating the object
    var arrayMaker = {
     someProperty: 'some value here',
     make: makeArray
    };
    
    //invoke the make() method
    arrayMaker.make('one', 'two');
    // => [ arrayMaker, 'one', 'two' ]
    // alternative syntax, using square brackets
    arrayMaker['make']('one', 'two');
    // => [ arrayMaker, 'one', 'two' ]
    

    The value of this became the object itself. You may be wondering why isn't it still window since that's how the original function had been defined. Well, that's just the way functions are passed around in JavaScript. Function is a standard data type in JavaScript, an object indeed; you can pass them around and copy them. It's as if the entire function with argument list and body was copied and assigned to make in arrayMaker. It's just like defining arrayMaker like this:


    var arrayMaker = {
     someProperty: 'some value here',
     make: function (arg1, arg2) {
      return [ this, arg1, arg2 ];
     }
    };
    

    JavaScript function invocation rule #2
    In a function called using the method invocation syntax, like obj.myFunction() or obj['myFunction'](), causes the value of this to be obj.

    This is a major source of bugs in event handling code. Look at these examples.

    
    
    
    
    
    


    Clicking the first button will display "btn1" because it's a method invocation and this will be assigned the owner object (the button input element.) Clicking the second button will display "window" because buttonClicked is being called directly (i.e. not like obj.buttonClicked().) This is the same thing that happens when we assign the event handler directly in the element's tag, as we have done for the third button. Clicking the third button does the same of the second button.

    That's another advantage of using a library like jQuery. When defining event handlers in jQuery, the library will take care of overriding the value of this and make sure it contains a reference to the element that was the source of the event.

    //using jQuery
    $('#btn1').click( function() {
     alert( this.id ); // jQuery ensures 'this' will be the button
    });
    

    3) + 4) Two more: apply() and call()

    The more you leverage functions in JavaScript, the more you find yourself passing functions around and needing to invoke them in different contexts. Just like jQuery does in the event handler functions, you'll often need to override the value of this. Remember I told you functions are objects in JavaScript? Functions have predefined methods, two of them are apply() and call(). We can use them to do precisely that kind of overriding.

    var gasGuzzler = { year: 2008, model: 'Dodge Bailout' };
    makeArray.apply( gasGuzzler, [ 'one', 'two' ] );
    // => [ gasGuzzler, 'one' , 'two' ]
    makeArray.call( gasGuzzler,  'one', 'two' );
    // => [ gasGuzzler, 'one' , 'two' ]
    

    The two methods are similar. The first parameter will override this. They differ on the subsequent arguments. Function.apply() takes an array of values that will be passed as arguments to the function and Function.call() takes the same arguments separately. In practice I believe you'll find that apply() is more convenient in most cases.

    JavaScript function invocation rule #3
    If we want to override the value of this without copying the function to another object, we can use myFunction.apply( obj ) or myFunction.call( obj ).

    5) Constructors

    We should be aware that there aren't classes in JavaScript and that any custom type needs a constructor function. It's also a good idea to define the methods of your type using the prototype object, which is a property of the constructor function. Let's create a small type ArrayMaker.

    //declaring the constructor
    function ArrayMaker(arg1, arg2) {
     this.someProperty = 'whatever';
     this.theArray = [ this, arg1, arg2 ];
    }
    // declaring instance methods
    ArrayMaker.prototype = {
     someMethod: function () {
      alert( 'someMethod called');
     },
     getArray: function () {
      return this.theArray;
     }
    };
    
    var am = new ArrayMaker( 'one', 'two' );
    var other = new ArrayMaker( 'first', 'second' );
    
    am.getArray();
    // => [ am, 'one' , 'two' ]
    

    Without the new operator your function will just be called like a global function and those properties that we are creating would be created on the global object (window.) Another issue is that, because you typically don't have an explicit return value in your constructor function, you'll end up assigning undefined to some variable if you forget to use new. For these reasons it's a good convention to name your constructor functions starting with an upper case character. This should serve as a reminder to put the new operator before the call.

    With that taken care of, the code inside the constructor is very similar to any constructor you probably have written in other languages. The value of this will be the new object that you are trying to initialize.

    JavaScript function invocation rule #4
    When used as a constructor, like new MyFunction(), the value of this will be a brand new object provided by the JavaScript runtime. If we don't explictly return anything from that function, this will be considered its return value.

     

    It's a wrap

    I hope understanding the differences between the invocation styles will help you keep bugs out of your JavaScript code. Some of these bugs can be very tricky to identify and making sure you always know what the value of this will be is a good start to avoiding them in the first place.


    My thanks to: http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx

    JavaScript series: http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx