Note that there are some explanatory texts on larger screens.

plurals
  1. POPrototypal inheritance and the value of 'this'
    primarykey
    data
    text
    <p>I'm building an app with several 'modules'. Each module requires a similar base set of functionality, so I have created a base module that each module will inherit from via prototypal inheritance. Some of the function names on the base module are quite long, and since these functions are used often, I would like to assign shorter names within each module, but this causes issues with the value of 'this' setting it equal to DOMWindow. </p> <p>Please see the code below:</p> <pre><code>var SAMPLEAPP = SAMPLEAPP || {}; //This is a base module that I want all other modules to inherit from SAMPLEAPP.Module = function(){ }; SAMPLEAPP.Module.prototype.someLongFunctionName = function(){ console.log(this); }; //This is a module that inherits from the base module SAMPLEAPP.RouterModule= function(){ var shortName = this.someLongFunctionName; //This correctly logs 'SAMPLEAPP.RouterModule', but I would rather not type //out this long function name each time I need to use the function this.someLongFunctionName(); //However, this code logs 'DOMWindow' when I would expect the value of 'this' //to be the same as the direct call to this.someLongFunctionName shortName(); }; SAMPLEAPP.RouterModule.prototype = new SAMPLEAPP.Module(); new SAMPLEAPP.RouterModule(); </code></pre> <p>My Question: How can I modify the code so that calling shortName() logs SAMPLEAPP.RouterModule? If possible, I would rather change the way the modules are defined than the actual call to shortName (i.e. shortname.call(this), defeats the purpose of creating an alias for someLongFunctionName)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload