Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How JavaScript object helps in avoiding method duplication

This article is inclined to touch on several areas on how object methods can be called, making use of JavaScript and avoiding method duplication.

Though it might seem very straight forward to call a JavaScript Object's methods, but implementing the same in real is never easy for the reason that there are quite a good number of ways involved in doing so. However each of these ways may produce an outcome for a method behaving in a different manner and sometimes even in unexpected ways.

Difference between Methods and Functions

It may seem that there is no difference between functions and methods. From technical point of view, they both are in JavaScript for the reason that all the functions belong to some object or the other. But, those methods that can be called where there is no object-dot prefix (object.) falls under the consideration of the functions. They are part of the global namespace. All of the global functions are actually taken care by the Window object however the point to note here is that there is no need of object-dot prefix. To put this as an example, let us take any global function such as alert (), isNaN(), or eval() and prepend the 'window.' object identifier to it:

alert('hello.'); window.alert('hello.'); //still works
 
isNaN('test'); //returns true
window.isNaN('test'); //still returns true
 
eval("isNaN('test');"); //also returns true!
window.eval("window.isNaN('test');"); //true as well

Piggybacking method making use of Function Call() and Apply()

    We have a function in JavaScript that in itself is an object having its own methods-call() and apply().

  • Both serve the same purpose
  • They permit an object to make use of another object's method for its own designs.
  • Though the entire thing may sound altogether different, however it helps you in saving duplicate methods across multiple objects.

  • Both methods accept this pointer as the first argument,
  • However call() takes each target function parameter separately.
  • And apply() expects an array of arguments as the second argument as shown below in the code

    Function.call(thisArg[, arg1[, arg2[, ...]]])
     
    Function.apply(thisArg[, argArray])

    The call() method signature is best known for

  • methods whose arguments are known beforehand.
  • Apply(), on the other side, is for

  • methods whose argument list can vary or is unknown.
  • Let us see some examples to clear this difference.

  • Assume Robert is a filter who has no methods of his own. His life would have been on a standstill if he were a Java of C++ class.
  • Now for the reason that he lives in JavaScript, he can use one of the Function methods to execute John's sayHello() method. Also as we are aware of the fact that the sayHello() method accepts only a name argument, the call() can be used and name can be passed to it in the following manner:
  • var John = {
      name: 'John',
      sayHello: function(name) {
        return 'Hi '+name+', I\'m ' + this.name;
      }
    };
     
    var Robert = {
       name: 'Robert'
    };
     
    alert(John.sayHello.call(Robert, name)); //outputs 'Hi John, I'm Robert'

    One of the good usage for the apply() method lies in the object creation and constructor chaining. The rationale is that each of the object will have a different set of constructor arguments.

    In the example given below, createObject() method is added to the Function object's prototype. This is for the reason that making use of this, we can apply it to any object's constructor function. The person object's initialization parameters are set with the help of an array of object literals. Each of the object literals contains the property name and associated value.

    Here if we use the apply() method, we can pass the array to the constructor function and in turn, it parses the property names and values to set them. After the creation of the object, the members of class can be accessed making use of usual object-dot (person.) notation:

    Function.prototype.createObject = function (aArgs) {
        var init       = this,
            fNewConstr = function () { init.apply(this, aArgs); };
        
        fNewConstr.prototype = init.prototype;
        
        return new fNewConstr();
    };
     
    var args = [{name: "Rob"}, {age: 29}, {liesAboutHisAge: true}]; var person = function() {
        for (var i = 0; i < arguments.length; i++) {
            var propName   = function(obj) { for(var name in obj) { return name; } }(arguments[i]);
            this[propName] = arguments[i][propName];
        }
    }.createObject(args);
     
    alert(person.name); // alerts "Rob"

    How to call an Instance Method without an Instance?

    One can make use of the call() and apply() methods to call the methods of an object that hasn’t been instantiated other than allowing an object to hijack another's methods. This is made possible because built-in objects like Strings and Arrays in JavaScript have the capability to store all their methods in the prototype property. The below lists the code that calls the String's substr() method directly:

    alert(typeof String); //displays 'function'
    var str = 'the brown cat jumped over the fence.'; alert(String.prototype.substr.call(str, 4, 5));

    You may come across some situations where there is absolutely no need to have instance of a certain object type however there is a requirement to get at some of its functionality. Below we have an instance of parameter relaying. Like we can pass parameters directly to a function or method, here the parameters are passed between each other. The perfect example of this is the function that uses some parameters and then passes the rest on to the next function. This can be achieved by calling the Array prototype's slice() method as mentioned below:

    function function1() {
      alert(John.sayHello(arguments[0]));
                                    //passes the last argument on
      function2.apply(arguments[1], Array.prototype.slice.call(arguments, 2)); }
     
    function function2() {  //only one argument passed
       alert(John.sayHello.call(this, arguments[0])); }
     
    function1("Robert", Robert, John.name);

    Conclusion

    Here is this article, we learned on several ways to call an object's methods in JavaScript and also passing parameters to a method. One can save a lot of method duplication and also cut down on your object instances making use of these methods.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login