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

Tagged:

Leave a comment