JavaScript Object-Oriented Programming - Accessor method that retrieves a property from the parent

Having trouble with implementing getters and setters for model objects in Angular. Facing an error:

TypeError: Cannot read property 'firstName' of undefined
at User.firstName (http://run.plnkr.co/AvdF2lngjKB76oUe/app.js:35:32)

The code snippet:

angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
      var intObj = { firstName: 'Brian' };
      $scope.user = new User(intObj);
  }]);

function ModelBase(wo) {
  this.wrappedObject = wo;

  this.onPropertyChanged = function(self, propertyName, oldValue, newValue) {
    //alert(self + ", " + propertyName + ", " + oldValue + ", " + newValue);
  }
}

var isDefined = function(value) {
    return typeof value !== 'undefined';
};

User.prototype = new ModelBase();
User.prototype.constructor = User;

function User(wo) {
  ModelBase.call(this, wo);

  this.firstName = function(value) {
    if(isDefined(value))
    {
      var oldValue = this.wrappedObject.firstName;
      this.wrappedObject.firstName = value;
    }
    else 
    {
      return this.wrappedObject.firstName; //(Line 32)
    }
  }
}

Seems like the getter is being called before wrappedObject is set on the base object. Any insights into what might be missing here? Included onPropertyChanged, but it's commented out to better illustrate the goal.

Plunker

Answer №1

The context gets lost within the firstName method. When Angular calls this method, it runs in the global object context. To resolve this issue, you can utilize the Function.prototype.bind method as a solution:

function User(obj) {
    ModelBase.call(this, obj);
    
    this.firstName = function(value) {
        if (isDefined(value)) {
            var prevValue = this.wrappedObject.firstName;
            this.wrappedObject.firstName = value;
            //onPropertyChanged(this.wrappedObject, 'firstName', prevValue, value);
        } else {
            return this.wrappedObject.firstName;
        }
    }.bind(this);
}

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

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

Having a slight hiccup with pixel alignment and browser compatibility in my jQuery animation

To emphasize a specific paragraph element, I developed a JavaScript function that displays it above a darkened background. My approach involved using jQuery to generate an overlay and then duplicating the targeted paragraph element while positioning it ab ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

Tips for assigning a standard or custom value using JavaScript

What is the best way to automatically assign a value of 0 to my input field when the user leaves it blank? Should I use an if statement { } else { } ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() => ...

combining input fields for editing as a single unit instead of individually

Current Situation : At the moment, I have a form where individual records of input fields such as firstName, lastName, and email can be edited and saved without any errors. Requirement : However, I now want to be able to edit and save the firstName and ...

Vue js version 2.5.16 will automatically detect an available port

Every time I run the npm run dev command in Vue.js, a new port is automatically selected for the development build. It seems to ignore the port specified in the config/index.js file. port: 8080, // can be overwritten by process.env.PORT, if port is in u ...

Invoking code behind functions through ajax requests to dynamically display items one by one

I'm currently working with calling code behind functions from an ajax call. I have recently developed a method called Post, which returns a list of values. My goal is to verify these values from the client side by displaying them in an alert message. ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

A clever method for implementing lazy-loading using mobx

Can you provide guidance on the most effective way to lazy load properties with MobX? I've been grappling with this issue for a few days now, and I've struggled to find suitable examples ever since strict mode was introduced. While I appreciate ...

Utilize AngularJS to present JSON data generated from PHP in a tabular format

After retrieving data from a MySQL database, I am formatting it into JSON. The fetch.php file: https://i.stack.imgur.com/4UbOs.png When I use echo $json;, the following is output to the console. [{"id":"1","emp_no":"1111","first_name":"1fname","last_n ...

Using Django Sessions for User Authentication in React Applications

Not a coding query, but rather a general one: When using default authentication in Django (session authentication), what does the frontend (in my case it's React) require? For instance, upon logging in on the browser via the front end login button, th ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

Is it possible to execute a function once another function has been called within a specific interval

Currently, I am working on a Greasemonkey script and have encountered an issue. The website contains a function that runs at regular intervals: jQuery(function1.run); setInterval(function1.run, function1.interval); I aim to execute my function immediatel ...

What is the best way to create 7 or 8 column grids with Vuetify's v-row and v-col components?

I understand that vuetify's grid system is based on a 12-column flex-box layout, but I would like to customize it to have 7 or 8 columns by default instead of the usual 12. In the code snippet below, you can see my attempt: <v-row> <v-col ...

Steps to turn off a Material UI CSS class for an element universally

Utilizing the Material UI Typography element with the css class MuiTypography-h1, I am seeking to globally disable its usage throughout the entire codebase. <Typography variant="h1" sx={{ width: '100px', height: '55px ...

When dynamically loading content with ajax, dynamic content fails to function properly

Currently, I am attempting to incorporate dynamic content loading after the user logs in by utilizing $.ajax. Here is how it's being done: $.ajax({ url: "functions.php", type: "GET", data: login_info, datatype: 'html', a ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

Amplify encounters the "Failed to load resource: the server responded with a status of 400" issue

I encountered an error while using Amplify, although the build was completed successfully. Failed to load resource: the server responded with a status of 400 manifest.json:1 The system is functional in the local environment. Below is the Package.json scri ...

Creating a star-based rating feature through directive implementation

Can anyone help me figure out why my static star rating system using angularjs/ionic is not showing up on the screen? I've been struggling with it and would appreciate some guidance. service.html <ion-list> <ion-item ng-repeat="busine ...