Just JavaScript - How Functions Become Methods
Written by Ian Elliot   
Monday, 26 March 2018
Article Index
Just JavaScript - How Functions Become Methods
The Solution - this
Onclick Example

Shared Instance Methods

final version in print book

Call and Apply

final version in print book

Early And Late Binding - the bind method

final version in print book

JustJavaScripticon

The Onclick example

The best known example, or is it complaint, about JavaScript's late binding is the mistake many beginners make when assigning an event handler that is also a method.

For example:

var myObject = {mySize: 99}; myObject.getSize=function() {
                    alert(this.mySize);
                 };
Button1.onclick=myObject.getSize;

Notice that assigning the Function object to a property of Button1 makes it a method of Button1 as well as of myObject - this is an example of one Function object serving two masters in that it is a method of myObject and Button1.

When you click the Button the Function is evaluated with this referencing the HTMLElement that is the Button. That is in this case the Function object is bound to the Button object.

The result is that the getSize function doesn't work and the beginner wastes a lot of time trying to debug the code. This is also how JavaScript gets a bad name.

Of course the correct way to do the job is to early bind the method.

myObject.getSize=function() {
                   alert(this.mySize);
                 }.bind(myObject);

With the addition of just bind(myObject) the event handler now works as the novice expects and displays the value of myObject.mySize.

A better way is to early bind the method when assigning it as the event handler:

Button1.onclick=myObject.getSize.bind(myObject);

It sometimes matters if methods are late or early bound - it all depends how you plan to use them. When you create a method early bind it to the object if you know that it will never be used with any other object, including instances created by a constructor. If this isn’t the case then early bind the method if you allow another object to make use of it as in the case of the Button and the event handler method.

Overriding Object Methods

final version in print book

Arrow Functions and this (ES2015)

Although arrow functions create Function objects in the usual way they don’t follow the same behavior with regard to this. An arrow function uses the value of this that is current in its context when it is declared and the Function object is created.

You can say that arrow functions don’t have a this but it is better to say that they don’t have a this of their own.

Notice that this is subtle because as an arrow function doesn’t have a this of its own the this current when it is declared is part of its execution context and included in its closure.

For example, if we define myObject as:

var myObject = {mySize: 99,
                getSize: ()=>{return this.mySize}
               };

Notice that the arrow function creates a Function object when myObject is created and at this time this is set to the global object. The this value is included in the closure and when you call the method this will still be the global object.

For example:

alert(myObject.getSize());

displays undefined unless there is a global variable called mySize.

If you declare an arrow function within a method defined in the usual way then the arrow function will have the same this as the method. If you think of arrow functions as lightweight utilities then this is exactly what you want.

For example:

var myObject = {
        mySize:99,
        getSize:function () {
        var myArrow = () => {
                    return this.mySize;};
        return myArrow();
        }
};

In this case myArrow is declared within the method and in this case the value of this will be whatever it is in the method call and

alert(myObject.getSize());

now works because this is set to myObject when the arrow function creates its Function object. When myArrow is executed this is still set to myObject.

As the this is included in the closure it doesn’t matter when myArrow is executed and this could be long after the method has finished executing. For example:

var myObject = {
     mySize: 99,
     getSize: function () { var myArrow = () =>
                          {return this.mySize;};
     setTimeout(function(){
                  alert(myArrow());
                } ,1000); }
};

This still displays 99 even though myArrow isn’t called until one second after the setTimeout is executed and the getSize method has finished executing.

Is the JavaScript way better?

JavaScript is certainly different and trying to make it look like the way other languages do the job is a big part of the problem.

The need to use a call context, i.e. this, is a consequence of treating functions as first class objects and this is very well worthwhile. Function objects live longer than the period where their code is being executed. As a result it converting them to methods with a default object reference is slightly more difficult. Some times you want the method to be always bound to the same object and in his case you need to manually apply early binding. If you want the method to work with a range of objects specified at call time then you need late binding which is the default if you use the call context this. You have great flexibility in how Function objects become methods.

JavaScript takes an approach that has a synergy in that all of the parts fit together and, yes, give you more than the sum of the parts.

As long as you understand all of the parts.  

Summary

  • Functions are just objects and can be properties of other objects.

  • A method is a function property that makes use of the object it is a property of in its code. 

  • To allow a method to reference the object it is a property of it is passed an execution context in this - which is a reference to the object involved in the function call. 
    If a function is called using 
    myObject.function()
    then this references myObject. We say that the function or method is bound to myObject.

  • Functions that are methods use
    this.myProperty
    to reference properties of the object they are bound to.

  • A Function object exists independently of any object that it is a property or method of. This means it can be referenced by other variables and the object it is bound to depends on how the function is called. A single Function object can be a method for many different objects and it can be just a Function object.

  • You can use apply and call to explicitly set the value of this and so borrow methods from other object and create ad-hoc methods that aren't properties of the object that they work with.

  • That is in JavaScript methods are late bound to their objects.

  • The bind method can be used to create a Function object bound to any specified object. That is myFunc.bind(myObject) creates a new Function object permanently bound to myObject with the same function body as myFunc.

  • You can late bind a method to an object using:
    myObject.property=function(parameters){
      function body using this
     };

  • You can early bind a method to an object using:myObject.property=function(parameters){
      function body using this
     }.bind(myObject);

  • In general you should use the default late bound method unless you need to assign or pass a method rather than a function when you should early bind. 

 

 

This is an extract from the book Just JavaScript by Ian Elliot.

Buy Now: from your local Amazon

Just JavaScript 
An Idiomatic Approach

JustJavaScriptSmall

A Radical Look At JavaScript

 

Most books on JavaScript either compare it to the better known class based languages such as Java or C++ and even go on to show you how to make it look like the one of these.

Just JavaScript is an experiment in telling JavaScript's story "just as it is" without trying to apologise for its lack of class or some other feature. The broad features of the story are very clear but some of the small details may need working out along the way - hence the use of the term "experiment". Read on, but don't assume that you are just reading an account of Java, C++ or C# translated to JavaScript - you need to think about things in a new way. 

Just JavaScript is a radical look at the language without apologies.

Contents

  1. JavaScript – Essentially Different

  2. In The Beginning Was The Object

  3. Real World Objects 

  4. The Function Object
          Extract - The Function Object
          Extract - Function Object Self Reference

  5. The Object Expression 

  6. Function Scope, Lifetime & Closure 

  7. Parameters, Returns and Destructuring
         Extract - Parameters, and Destructuring 

  8. How Functions Become Methods

  9. Object Construction

  10. The Prototype
         Extract - ES2015 Class and Extends 

  11. Inheritance and Type

  12. The Search For Type ***NEW!

  13. Property Checking

Buy Now: from your local Amazon

Also by Ian Elliot 
JavaScript Async: Events, Callbacks, Promises and Async Await
Just jQuery: The Core UI 
Just jQuery: Events, Async & AJAX  

 

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, FacebookGoogle+ or Linkedin.

Python

 



 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Tuesday, 01 May 2018 )