Category Archives: JavaScript

Different type of methods in Javascript

Object Creation:

Unlike most other object-oriented languages, JavaScript doesn’t actually have a concept of classes. In most other object-oriented languages you would instantiate an instance of a particular class, but that is not the case in JavaScript. In JavaScript, objects can create new objects, and objects can inherit from other objects. This whole concept is called prototypal inheritance and will be discussed more later in the “Public Methods” section. Fundamentally, though, there still needs to be a way to create a new object, no matter what type of object scheme JavaScript uses. JavaScript makes it so that any function can also be instantiated as an object. In reality, it sounds a lot more confusing than it is. It’s a lot like having a piece of dough (which is a raw object) that is molded using a cookie cutter (which is an object constructor, using an object’s prototype).

// A simple function which takes a name and saves it to the current context
function User( name ) {
this.name = name;
}

// Create a new instance of that function, with the specified name
var me = new User( “My Name” );

// We can see that its name has been set as a property of itself
alert( me.name == “My Name” );

// And that it is an instance of the User object
alert( me.constructor == User );

// Now, since User() is just a function, what happens
// when we treat it as such?
User( “Test” );

// Since its ‘this’ context wasn’t set, it defaults to the global ‘window’
// object, meaning that window.name is equal to the name provided
alert( window.name == “Test” );

The above listing shows the use of the constructor property. This property exists on every object and will always point back to the function that created it. This way, you should be able to effectively duplicate the object, creating a new one of the same base class but not with the same properties.

An Example of Using the Constructor Property

// Create a new, simple, User object
function User() {}

// Create a new User object
var me = new User();

// Also creates a new User object (from the constructor reference of the first)
var you = new me.constructor();

// We can see that the constructors are, in fact, the same
alert( me.constructor == you.constructor );

Now that we know how to create simple objects, it’s time to add on what makes objects so useful: contextual methods and properties.

Public Methods:

Public methods are completely accessible by the end user within the context of the object. To achieve these public methods, which are available on every instance of a particular object, you need to learn about a property called prototype, which simply contains an object that will act as a base reference for all new copies of its parent object. Essentially, any property of the prototype
will be available on every instance of that object. This creation/reference process gives us a cheap version of inheritance.

Since an object prototype is just an object, you can attach new properties to them, just like any other object. Attaching new properties to a prototype will make them a part of every object instantiated from the original prototype, effectively making all the properties public
(and accessible by all). Example of an Object with Methods Attached Via the Prototype Object.

// Create a new User constructor
function User( name, age ){
this.name = name;
this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
return this.name;
};

// And add another function to the prototype
// Notice that the context is going to be within the instantiated object
User.prototype.getAge = function(){
return this.age;
};

// Instantiate a new User object
var user = new User( “Bob”, 44 );

// We can see that the two methods we attached are with the
// object, with proper contexts
alert( user.getName() == “Bob” );
alert( user.getAge() == 44 );

Simple constructors and simple manipulation of the prototype object is as far as most JavaScript developers get when building new applications. In the rest of this section I’m going to explain a couple other techniques that you can use to get the most out of your object oriented code.

Private Methods:

Private methods and variables are only accessible to other private methods, private variables, and privileged methods (discussed in the next section). This is a way to define code that will only be accessible within the object itself, and not outside of it. This technique is based on the work of Douglas Crockford, whose web site provides numerous documents detailing how object-oriented JavaScript works and how it should be used:

• List of JavaScript articles: http://javascript.crockford.com/
• “Private Members in JavaScript” article: http://javascript.crockford.com/private.html

Let’s now look at an example of how a private method could be used within an application,
as shown in below listing. 

Example of a Private Method Only Usable by the Constructor Function.

// An Object constructor that represents a classroom

function Classroom( students, teacher ) {
   // A private method used for display first student
   function disp() {
   alert(‘Classroom created’);
   }
   // Store the class data as public object properties
   this.students = students;
   this.teacher = teacher;
   // Call the private method to display the message at the time of object creation
   disp();
}

// Create a new classroom object
var class = new Classroom( [ “John”, “Bob” ], “Mr. Smith” );

// Fails, as disp is not a public property of the object
class.disp();

While simple, private methods and variables are important for keeping your code free of collisions while allowing greater control over what your users are able to see and use. Next, we’re going to take a look at privileged methods, which are a combination of private and public methods that you can use in your objects.

Privileged Methods:

Privileged methods is a term coined by Douglas Crockford to refer to methods that are able to view and manipulate private variables (within an object) while still being accessible to users as a public method. Below listing shows an example of using privileged methods.

Example of Using Privileged Methods

// Create a new User object constructor
function User( name, age ) {
    // Attempt to figure out the year that the user was born
    var year = (new Date()).getFullYear() – age;
    // Create a new Privileged method that has access to
    // the year variable, but is still publically available
    this.getYearBorn = function(){
    return year;
    };
}
// Create a new instance of the user object
var user = new User( “Bob”, 44 );

// Verify that the year returned is correct
alert( user.getYearBorn() == 1962 );

// And notice that we’re not able to access the private year
// property of the object
alert( user.year == null );

In essence, privileged methods are dynamically generated methods, because they’re added to the object at runtime, rather than when the code is first compiled. While this technique is computationally more expensive than binding a simple method to the object prototype, it is also much more powerful and flexible. 

Static Methods :

The premise behind static methods is virtually identical to that of any other normal function. The primary difference, however, is that the functions exist as static properties of an object. As a property, they are not accessible within the context of an instance of that object; they are only available in the same context as the main object itself. For those familiar with traditional classlike inheritance, this is sort of like a static class method. In reality, the only advantage to writing code this way is to keep object namespaces clean. Below listing shows an example of a static method attached to an object.

A Simple Example of a Static Method

// A static method attached to the User object
User.cloneUser = function( user ) {
   // Create, and return, a new user
   return new User(
   // that is a clone of the other user object
   user.getName(),
   user.getAge()
   );
};
Static methods are the first methods that we’ve encountered whose purpose is purely organizationally related. A fundamental aspect of developing professional quality JavaScript is its ability to quickly, and quietly, interface with other pieces of code, while still being understandably accessible.

Content impressed from Pro JavaScript Techniques– John Resig

Ajax Vs Form Submission

I read question/answer about posting the web page in stackoverflow. Presented here for your attention.

<html>
<head>
    <meta name=”viewport” content=”width=device-width” />
    <title>Index</title>
</head>
<body>
    <div>
        <form action=”Home” method=”post”>
            Username:
            <input type=”text” name=”user”>
            Password:
            <input type=”password” name=”pwd”>
            <input type=”submit” value=”Submit”>
        </form>
    </div>
</body>
</html>

Before discussing about difference between the submissions, find below some differences between id and name attribute:

   *  the name attribute relates to how data is labeled when sent to server, and multiple elements may share the same name. When page is posted the name/value pair will be sent to server to easily corelate the value against the control/variable in server. The id attribute on the other hand is for identifying one unique element for the purposes of scripting, styling, or addressing.

   * The use of the name attribute on other elements than form controls was in HTML4.01 the same as that of id, but it allowed for a wider set of characters than the id attribute and wasn’t controlled in quite the same way. Because of this ambiguity the W3C decided to deprecate/remove name attribute on those elements in favor for the unambigous id attribute in XHTML. This is also connected to another detail of XML however – only one attribute of any element may be of the type ID, which would not be the case if they let name stay on the element but corrected the ambiguity problems.

   * As the name attribute didn’t work the same on those two sets of elements, if was best to remove on of them.

In short, for backwards compatibility you should use name and id attribute both, both set to the same value, for all elements except form controls if you use HTML4.01 or XHTML1.0 Transitional. If you use XHTML1.0 Strict or later you should use only id. For form controls you should use name for what you want the form to send to the server and, and only use id for styling or addressing reasons.

The method attribute in form element specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method=”get”) or as HTTP post transaction (with method=”post”).

Notes on GET in Form element:

    * Appends form-data into the URL in name/value pairs [http://localhost:1158/Home?user=ala&pwd=rtc]
    * The length of a URL is limited (about 3000 characters)
    * Never use GET to send sensitive data! (will be visible in the URL)
    * Useful for form submissions where a user want to bookmark the result
    * GET is better for non-secure data, like query strings in Google

Notes on POST in Form element:

    * Appends form-data inside the body of the HTTP request (data is not shown is in URL – http://localhost:1158/Home. You will usually read this in asp.net/asp.net mvc by using Request.Form Or model binder specifically in asp.net mvc)
    * Has no size limitations
    * Form submissions with POST cannot be bookmarked

You can even post the base by using Ajax/XmlHttpRequest request. But in ajax you will have to manually form the request and parse the response and update the page.

POSTing, as compared to GETting, is a different HTTP method with different implementation and semantics. Ajax, or XmlHttpRequest, has its counterpart in normal requesting/navigation. You can use POST or GET for both XmlHttpRequest and normal navigation and form submission (well, POST is always a “form submission”).

The difference between XmlHttpRequest and normal requests is that a normal request replaces the page with a new page.

You could write just about any website using only Ajax to get data and change the DOM; that’s mainly how Gmail works. There are no “form submissions” in the traditional sense. But there are still GETs and POSTs because the server and browsers interpret the results differently. GET is supposed to be idempotent; POST is meant for operations that change the state on the server. For example, an ecom transaction should be a POST. This doesn’t change when using Ajax because you want proxy servers to also understand that this is a POST and that they shouldn’t try to cache the response.

There are also advantages and disadvantages to using GET vs POST. You can’t bookmark the results of a POST because the parameters are hidden. You can’t GET something with parameter values of unlimited length because IE only supports about 2000 chars.

Also there are disadvantages to using Ajax vs normal submissions; you can’t bookmark the resulting page; the back button won’t work as expected. You can’t upload a file using Ajax. But with Ajax you could minimize the data transfered and also provide convenient updates to a page (such as monitoring the status of a long process) without annoying flickering or refreshing.

In summary the two request types, Ajax and traditional form submission, can both be used with GETs and POSTs, and there are pros and cons for each. Neither type can do everything the other can and so you can expect to see a mix for the forseeable future.

Host objects Vs Native objects In JavaScript

The native objects are sometimes referred to as “global objects” since they are the objects that JavaScript has made natively available for use. Do not confuse the term global object with the “head” global object that is the topmost level of the scope chain, for example, the ‘window’ object(head) in all web browsers

Below find the list of 9 native object constructors that come pre-packaged with JavaScript:
✴ Number() ✴ String() ✴ Boolean() ✴ Object() ✴ Array() ✴ Function() ✴ Date() ✴ RegExp() ✴ Error()

JavaScript is mostly constructed from just these 9 objects (as well as string, number, and boolean – primitive values – which equality is based on value not ref.).

If you called the constructors(The Number() , String() , and Boolean() as like) directly, then a complex object is returned. If you simply express a number, string, or boolean value in your code (primitive values like 5, “foo” and true), then the constructor will return a primitive value instead of a complex object value.


<script>
var myNumber = new Number(23); // an object
var myNumberLiteral = 23; // primitive number value, not an object - literal way of saying

var myString = new String('male'); // an object
var myStringLiteral = 'male' // primitive string value, not an object - literal way of saying


myObject = new Object(); // an object
var myObjectLiteral = {}; // literal way of saying

var myArray = new Array('foo', 'bar'); // an object
var myArrayLiteral =['foo', 'bar']; // literal way of saying

var myFunction = new Function("x", "y", "return x*y"); // an object
var myFunctionLiteral = function(x, y) {return x*y}; // literal way of saying
</script>

The point here is that the above said native JavaScript objects and “head” object are different. We should be aware that the environment (e.g. a web browser) in which JavaScript is executed typically contains what are known as host objects. Host objects are not part of the ECMAScript implementation, but are available as objects during execution. Of course, the availability and behavior of a host object depends completely on what the host environment provides. For example, in the web browser environment the window/head object and all of its containing objects (excluding what JavaScript provides) are considered host objects. We examine the properties of the window object below.

<script>
for (x in window) {
console.log(x); //logs all of the properties of the window/head object
}
</script>

By executing this, We might have noticed that native JavaScript objects are not listed among the host objects. Itʼs fairly common that a browser distinguishes between host objects and native objects.

As it pertains to web browsers, the most famous of all hosted objects is the interface for working with HTML documents, also known as the DOM. Below, is a method to list all of the objects contained inside the window.document object provided by the browser environment.

<script>
for (x in window.document) {
console.log();
}
</script>

The JavaScript specification does not concern itself with host objects and vice versa. There is a dividing line between what JavaScript provides and what the host environment provides, and these two should not be confused.

The host environment (e.g. a web browser) that runs JavaScript code typically provides the head object (e.g. window object in web browser) where the native portions of the language are stored along with host objects (e.g. window.location in web browser) and user-defined objects (e.g. the code your write to run in the web browser).

It’s not uncommon for a web browser manufacturer as the host of the JavaScript interrupter to push forward the version of JavaScript or add future specifications to JavaScript before they have been approved (e.g. Mozilla’s Firefox JavaScript 1.6 , 1.7 , 1.8 , 1.8.1 , 1.8.5 ) – this article is based on JavaScript 1.5, ECMA-262, Edition 3.

Cody Lindley @ JavaScript Enlightenment

Unobtrusive JavaScript – Dependency Injection in JavaScript

“Unobtrusive JavaScript” is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally understood to include:

        Separation of functionality (the “behavior layer”) from a Web page’s structure/content and presentation
        Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
        Progressive enhancement to support user agents that may not support advanced JavaScript functionality

So it is basically separating behavior or javascript from presentation or html.

 <input type="button" value="Click me" onclick="handleClick()">  

From a purely functional perspective, there’s nothing wrong with this code—it just works as expected and runs the handleClick JavaScript function whenever the user clicks the button. This approach is largely acceptable when JavaScript is just used to spice up web pages; however, it becomes unwieldy when the amount of JavaScript code represents a significant portion of the page or the view.

With CSS, you write plain HTML without inline style information and add style to elements using CSS classes. Likewise, you avoid using event handler attributes (onclick,onchange,onblur,and the like)and use a single JavaScript function to attach handlers when the DOM is ready.
Here’s a concise but effective example of unobtrusive JavaScript.

<script type="text/javascript">
$(document).ready(function () {
$("#Button1").bind("click", function () {
var date = new Date().toDateString();
alert(date);
});
});
</script>
<h2>JavaScript Patterns</h2>
<fieldset>
<legend>#1 :: Click</legend>
<input type="button" id="Button1" value="Today" />
</fieldset>

You can move the entire <script> block to a separate JavaScript file and have your view be clean and readable.

Unobtrusive JavaScript establishes a fundamental principle—any behavior in any web page has to be an injectable dependency and not a building block. There will be more and more situations in which you need to download or configure the script code on the fly based on run-time conditions, such as the capabilities of the browser (or mobile device). To address these scenarios properly, start thinking about JavaScript as an injectable dependency.

Unobtrusive JavaScript is a wider and deeper concept. It aims at getting a neat separation between content (HTML document), presentation (CSS style sheets), and behavior (script code). Ideally, a page should come back to a plain sequence of document tags—headers, P, and maybe the new tags coming up in HTML 5 such as section, footer, and article. The page should be able to present its content in a readable way as plain HTML. Next, you addCSS and the choice of different CSS styles on, say, a per-device basis. Next up, you add JavaScript.

Both CSS and JavaScript should be linked in a single place, and it should be easy to switch them on and off. As a software developer, you probably use forms of dependency injection every day. Well, just think of CSS and JavaScript code as dependencies you inject into an HTML page.

There is more to unobstrusive javascript as can be checked out on wikipedia article.

Dino Esposito