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

Utilize an Express.js controller to retrieve information from an API service and display it on the view

I need assistance with connecting an ExpressJS web app to an API system that responds only with JSON objects. The API system example is: http://example.com/user/13 response: {name:'Aesome 1', age: '13'} The ExpressJS web app cre ...

Tips for enabling mouse wheel zoom on a three.js scene

I have a straightforward three.js graphic that I wanted to make zoomable by using the mouse wheel. I attempted to implement solutions from this and this question in order to achieve this feature. Ideally, I want users to be able to zoom in or out of the gr ...

What is the best way to connect the imagemap shape with the checkbox?

I need assistance with synchronizing an imagemap collection of shapes and checkboxes. How can I ensure that clicking on a shape selects the corresponding checkbox, and vice versa? Imagemap: <div class="map_container"> <%= image_tag("maps/main ...

Angular.js Integration for Custom Single Sign On

I currently have 3 websites built using Angular.js 1.5.8 and I want to integrate them with a single sign-on web application for centralized authentication management. How can I achieve this without relying on external libraries or frameworks? It seems ch ...

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

Is it possible to show more than five buttons in an Amazon Lex-v2 response display?

Here is the sessionState object I am working with: { "sessionAttributes": {}, "dialogAction": { "type": "ElicitSlot", "slotToElicit": "flowName" }, "intent": { "name": &q ...

AngularJS - Error encountered while configuring $httpProvider with an unknown provider

In this code snippet: myApp.config(['$httpProvider', function($httpProvider, $cookieStore) { $httpProvider.defaults.withCredentials = true; $httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStor ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

Navigating to a specific element following an AJAX request

Can't seem to get the page to scroll to a specific element after an ajax call. What could be causing this issue? index.php <style> #sectionOne { border: 1px solid red; height: 100%; width: 100%; } #sectionTwo { border: 1px solid blue; heigh ...

A step-by-step guide on incorporating the C3 Gauge Chart into an Angular 5 application

I have been attempting to incorporate the C3 Gauge Chart from this link into a new Angular 5 application. Below is my code within chart.component.ts : import { Component, OnInit, AfterViewInit } from '@angular/core'; import * as c3 from &apos ...

Vertically align the left div in the center, while maintaining the standard alignment of the right div

I have been experimenting with Bootstrap 4 and attempting to implement the Vertical alignment feature as outlined on the webpage: https://getbootstrap.com/docs/4.0/layout/grid/ Despite reviewing my code multiple times, I am unable to identify the mistake ...

Displaying JSON data based on a specific key

My current challenge involves dealing with a JSON string structured like this: {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]} As part of my learning process in Javascript and AJAX, I am attempting to display the different values based ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this: @WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true) public class CreateCon extends ...

Authenticating the identity of the client application - the client is currently within the browser

I have a PHP backend (although it's not really important) and a Javascript client that runs in the browser. Here is how the application operates: The user accesses a URL and receives raw templates for rendering data An Ajax GET query is sent to the ...

Stop unauthorized entry into JavaScript files

Is there a method to secure JavaScript files from unauthorized access? <script src="JS/MyScript.js" type="text/javascript"> It is crucial that users are unable to access the MyScript.js file. I am seeking advice on how to achieve this. Is it even ...

Creating a video that plays frame-by-frame on an HTML5 canvas and can be controlled with a slider

I am currently working on a walkthrough video where the user has the ability to slide a UI slider across the screen, causing the camera to navigate through a 3D space. The video itself has been exported in jpg frames, numbered from 0 to 350.jpg. My appro ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...