Can you clarify the issue with the Uncaught TypeError stating that Property 'x' of object [object Object] is not a function?

Could someone please clarify why the outcomes differ in each scenario described below? I am trying to grasp the way JavaScript interacts with scope, assuming that is the root of the issue. In the initial example, my code behaves as expected.

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

};

var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };


var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());

If I relocate the addSalaryFunction inside the Employees function and position it beneath this.addSalary, I encounter an Uncaught TypeError.

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

    var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };
};

var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());

However, if I move the addSalaryFunction above this.addSalary, the code functions correctly again. My IDE indicates that the local variable addSalaryFunction seems redundant.

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

};


var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());

Answer №1

The reason for the error is that you are attempting to assign a function before it has been created.

this.addSalary = addSalaryFunction; // At this point, the function does not exist yet

//...

var addSalaryFunction = function(addition) {  // The function is defined here, but it's too late
    this.salary = this.salary + addition;
};

By moving the variable assignment above

this.addSalary = addSalaryFunction
, you create the function before referencing it.

var addSalaryFunction = function(addition) {  // Function definition goes first
    this.salary = this.salary + addition;
};
this.addSalary = addSalaryFunction;  // Now the function can be assigned and accessed

If you had used function declaration syntax instead, the initial version would work because function declarations are "hoisted" to the top of the scope.

this.addSalary = addSalaryFunction; // Works due to hoisting

//...

// This function is magically hoisted to the top
function addSalaryFunction(addition) {
    this.salary = this.salary + addition;
}

Answer №2

The reason the second method fails is that addSalaryFunction is being called before it is defined.

To simplify, you can just define it like this:

this.addSalary = function(addition) {
    this.salary += addition;
}

Answer №3

In a more simplified manner:

function exampleOne() {
    var num = val;
    var val = 4;
    return num;
};

function exampleTwo() {
    var value = 4;
    var num = value;
    return num;
};

Certainly, exampleTwo() will return 4. On the other hand, exampleOne() encounters an issue as it attempts to access the value of val before it has been defined, resulting in undefined being returned. Declarations for variables are elevated to the top within their scope, but initializations are not.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct way to upload an image using the Express static middleware?

Just diving into express, I have this setup in my server: app.use(express.static(path.join(__dirname, 'includes'))); When it comes to my client-side JavaScript, I'm simply using the URL like so: var img = $("<img />").attr('s ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

AngularJS: Retrieve individual objects from an array and subsequently initiate asynchronous requests

I am working with two tables, Category and Products, linked by a 1-N cardinality relationship. https://i.sstatic.net/e6C2y.png My goal is to retrieve all products belonging to a specific category. https://i.sstatic.net/yDrjr.png Here is the HTML table ...

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Using jQuery to loop through a table and choose dropdown menus

My task seemed simple at first. I have a table of drop-down lists, with a text box at the end of each line. All I need to do is loop through each row of the table, retrieve the value from the "hours dropdown" and multiply it by the value from the "rate d ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

What is the best way to ensure a consistent time interval between invoking two functions in JavaScript?

Is there a way to create a code that will call one function, let's say toStart(), and then immediately call another function, toStop(), exactly two seconds after the first function is initiated? I want this process to continue until a specific button, ...

Timeout during the beforeLoad event

I am currently working on writing some ExtJS 4 script and have come across the following code: var companyStoreModel = Ext.create('Ext.data.Store', { model: 'CompanyDataModel', proxy: { type: 'ajax&apos ...

"Exploring the powerful combination of React.js with DataGrid

I'm in search of a datagrid solution for my React.js project. I've tried out a few options, but haven't found exactly what I'm looking for. The datagrid needs to look good on smaller screens, like mobile phones. It's important tha ...

The backdrop moving in a reverse direction

I recently made a tweak to this code that successfully moves the background in the opposite direction of the scroll. However, there is now an issue where it leaves a blank space at the top, even when the background is set to repeat. The change I made was s ...

Rubaxa's sorting feature conceals floating entities but not the real rows

I have implemented the Sortable plugin by Rubaxa to rearrange rows in a Bootstrap table. Each row in the table contains Bootstrap inputs within its cells. Although the rows can be sorted smoothly, the "ghost" image that appears does not include the input ...

Encountered an issue during the package installation process in Next.js

PS E:\web dev 2024\threads> & npm install @clerk/nextjs @uploadthing/react mongoose svix uploadthing Unidentified symbol found in original text. At line:1 char:15 + & npm install <<<< @clerk/nextjs @uploadthing/react mongo ...

SlickGrid cannot function without a proper container, unfortunately #myGrid is not present in the DOM

I've been attempting to incorporate SlickGrid Dataview with Json, however, I have encountered a persistent error. The error message states: "JavaScript runtime error: SlickGrid requires a valid container, #myGrid does not exist in the DOM." <div i ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Utilize SectionList and a custom header view on Y to achieve a translation effect that creates a visually appealing empty space as

Hello everyone, I am fairly new to React Native and the Animated API. My goal is to create a simple parallax header and an Animated SectionList similar to this demonstration. https://i.stack.imgur.com/R2GBP.gif Below is a snippet of my code: export defa ...

Ways to pause and restart an animation without removing the initial tag object?

I'm attempting to reset an object's animation back to its starting point so I can initiate it from the beginning. function restartAnimation(node, from, to) { let duration = node.style.animationDuration; node.style.animationDuration = "0s"; ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...