What is preventing me from utilizing my JavaScript constructor function externally?

I have a question about how I create my object:

var myViewModel = new MyViewModel("other");

Why am I unable to call myViewModel.setHasOne(value) from outside the viewmodel?

Whenever I try, I encounter this error message:

Uncaught TypeError: Cannot call method 'setHasOne' of undefined

Although I can set the properties directly, I am keen on understanding how to achieve it using a method.

Below is the function I am referring to:

function MyViewModel(other) {

    var self = this;    
    self.other = other; 
    self.hasOne = false;

    this.setHasOne= function (value) {
        self.hasOne = value;
    };          

    return this;        
}

Answer №1

It seems like your code is error-free and should work fine, so the issue might be a simple typo somewhere. The error message indicates that the problem lies not in defining the method itself, but rather in the instance of your class. Specifically, the error message reads:

Uncaught TypeError: Cannot call method 'setHasOne' of undefined

This error suggests that the variable "myViewModel" is undefined for some reason, which leads to it being unable to locate "setHasOne" for an undefined value.

Regarding your code structure, having methods defined inside the constructor is known as "Privileged Methods". These methods have access to private variables defined within the constructor. However, if you don't need this feature, it would be more efficient to define your method as a "Public Method". Public methods share memory space across all instances of the class, making them more optimal in such cases.

Answer №2

Check out this code snippet:

function AnotherViewModel(data) {

var vm = this;    
this.data = data; 
this.hasValue = false;

}
AnotherViewModel.prototype.setHasValue = function(boolValue) {
  this.hasValue = boolValue;
};

Remember: you can omit the return statement in the constructor since this is already accessible.

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

I'm encountering some issues with routing within Node.js and Express framework

I have developed a single page application (SPA) using React framework. Currently, I am working on creating an API with Express in Node.js for my app. Below is the code snippet of my server: const express = require('express'); const app = expr ...

Having trouble converting Buffered Byte Array into Image in Browser

Hello there! I am currently facing an issue while attempting to generate an image from a buffered byte array. The reason behind this is that I need to transfer the image from the server to the client using JSON. Below is the code snippet in question: The ...

What is the best way to add a blob to the document object model (

I am a beginner when it comes to working with blobs, and I am looking for some guidance to avoid wasting hours on unsuccessful brute-force attempts. I have been using the PHP code below (sourced from here) to retrieve the base64-encoded image from my data ...

Setting a default value in a drop-down menu in a React Native application

Within my array of 5 values in the "Options" props, I want to set a default value of "Please Select" defined in the state. However, when trying to retrieve it in the Value props, an error is occurring with a message saying "Label of undefined". Essential ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Guidelines for accessing the value of the parent function upon clicking the button within the child function?

I have a pair of buttons labeled as ok and cancel. <div class="buttons-div"> <button class='cancel'>Cancel</button> <button class='ok'>Ok</button> </div> The functions I am working wi ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

What is the best way to create a reactive prop within this Vue 3 application?

I've been developing a news application using Vue 3 along with the News API. My current focus is on implementing a search feature. Within my App.vue file, I have: <template> <TopBar @search="doSearch" /> <div class=" ...

Error: The XPath expression provided is invalid for use with the scrollIntoView function in Selenium

My task involves utilizing Python to extract data from a website that features a filter pane requiring scrolling. I came across a code snippet that aids in navigating through a list of elements by iterating through a loop. recentList = driver.find_element ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...

Error: The function "navigate" has not been declared or defined

Just starting out in reactjs and embarking on a new project. I've successfully implemented a register and login function using firebase, but hit a snag when trying to navigate to a new page like the dashboard upon user login, I encountered this error: ...

Limiting the amount of blogs shown on a single page can be achieved with Yii 1 and PHP

I have successfully implemented a feature to display blogs on one page. However, I now want to modify it so that only 5 blogs are shown per page and the user can click on a "next page" button to view the next set of 5 blogs. Here is the code snippet from ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

basic fading javascript image rotator

While looking for a simple fade image rotator, I stumbled upon this old post: Simple fade javascript image rotator request I finally found what I was searching for: $(function() { $('#fader img:not(:first)').hide(); $('#fader img').c ...

Using Jquery to hide or show objects within a <div> when clicked

My goal is to create a webpage that displays three different contents based on which button is clicked. Below is the code for reference: I want the page to show three specific sections: A search bar only when the 'search' button is clicked, T ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Generate a custom Elementor shortcode dynamically using JavaScript

I have a custom-built website using WordPress and Elementor. I am running code through the html element in Elementor to display dropdown menus. When a value is selected from each dropdown and the button is clicked, the values are stored in variables and th ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...