JavaScript: lexical scoping issue using new keyword constructor while adding inner function?

When using constructor functions with inner functions, a common lexical scoping issue arises where the inner function cannot access the constructor's this context. This happens because inner functions have their own execution context.

The Problem

Inner functions don't inherit the this binding from their parent constructor, leading to undefined or incorrect values when trying to access constructor properties.

function Employee() {
    this.technologyName = "JavaScript";
    
    function workingTechnology() {
        // 'this' here refers to global object, not Employee instance
        console.log("Technology:", this.technologyName); // undefined
    }
    
    workingTechnology();
}

var employee = new Employee();
Technology: undefined

Solution: Store Reference to 'this'

The solution is to store the constructor's this reference in a variable that the inner function can access through closure:

function Employee() {
    this.technologyName = "JavaScript";
    var self = this; // Store reference to constructor's 'this'
    
    function workingTechnology() {
        console.log("I am working with " + self.technologyName + " Technology");
    }
    
    workingTechnology();
}

var currentTechnology = new Employee();
I am working with JavaScript Technology

Alternative: Arrow Functions

Arrow functions inherit this from their surrounding scope, providing a cleaner solution:

function Employee() {
    this.technologyName = "JavaScript";
    
    const workingTechnology = () => {
        console.log("I am working with " + this.technologyName + " Technology");
    };
    
    workingTechnology();
}

var employee = new Employee();
I am working with JavaScript Technology

Comparison

Method Compatibility Readability
Store this reference All JavaScript versions Clear but verbose
Arrow functions ES6+ only Clean and concise

Conclusion

Use a variable to store the constructor's this reference for inner functions to access. Arrow functions provide a modern alternative by inheriting the parent scope's this.

Updated on: 2026-03-15T23:19:00+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements