Obtainer that yields the function opposed to a "return" value

For my JavaScript project, I am experimenting with using getters and setters. I'm fetching a JSON object using jQuery's get method and setting the value with a setter. While I can successfully display the content within the setter function through an alert, I am facing an issue when trying to retrieve the value using a getter - instead of the expected value, I receive the entire function.

Here is the snippet of my code:


function DataHandler() {
  this.setJson = function(js) {
    json = js;
  }
  this.getJson = function() {
    return json;
  }
}
dataObj = new DataHandler();
$.get("json.php", function(data) {
  dataObj.setJson(data);
},"json");

alert(dataObj.getJson);

Upon running the alert, I get the following output:

function () {
    return json;
}

Even when attempting to use prototype, the result remains the same.

Answer №1

I completely agree with the earlier feedback provided by other users. It's important to remember to call the getter-function in order to retrieve the "json" value.

You may want to consider declaring the json variable as well, unless it needs to be accessed globally in some way.

It appears that you are combining various object construction patterns. One option is the functional pattern, which creates "private" variables within a closure (such as `json`), while also utilizing prototypical inheritance to attach getters/setters to `this` inside the constructor function. Consider sticking to one approach for consistency.

For example: encapsulating privates within a closure.

function _bd() {
   var json;
   var that = {};
   that.setJson = function(js) {
     json = js;
   }
   that.getJson = function() {
    return json;
   } 
   return that;
 } 
 var bd = _bd();
 $.get("json.php", function(data) {
   bd.setJson(data);
   alert(bd.getJson());
 },"json");

Another approach could be an Object-Oriented style using constructor functions.

function BD(){
  this._json = null;
}
BD.prototype = {
  getJson: function(){
    return this._json;
  },
  setJson: function(json){
    this._json = json;
  }
};

 var bd = new BD();
 $.get("json.php", function(data) {
   bd.setJson(data);
   alert(bd.getJson());
 },"json");

While there may be valid reasons for using a hybrid style, consistency between approaches can help streamline your code.

If you're interested in implementing "real" getters (despite the complex syntax), you can try:

function BD(){
   this._json = null;
}
Object.defineProperty(BD.prototype,"json",{
    get: function(){
       return this._json;
    },
    set: function(json){
       this._json = json;
    }
});

var bd = new BD();
bd.json = {a: "test"}; 
console.log(bd);

Answer №2

It was mentioned in the feedback that:

alert( bd.getJson() );

The reason you are seeing the function string is because you have not executed the function yet

If you try to access the result before it is returned, you may receive nothing or possibly undefined.

$.getJson
(
   success : function() { alert( bd.getJson() ); }
);

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

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...

Ensuring promise resolutions in a chain using Angular JavaScript before delivering a final result

I have a scenario in Angular where I am using a chain of promises and I want to ensure that a value is returned at the end of the chain: this.calculateeventsattended = function(username) { var Attendees = Parse.Object.extend("Attendees"); var User = ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...

Introduce new router events, routeChangeStart and routeChangeComplete, within the client-side components of next js 14

I am currently working on a Next.js v14.0.4 project and I am facing an issue with implementing a top loader progress bar using the NProgress package for route changes triggered by Link or router.push(). The handleRouteChangeStart and handleRouteChangeCom ...

Creating intricate JavaScript objects for JSON API integration can be accomplished by following these steps:

Here is a sample JSON structure used for querying an API: "order_items": [ { "menu_item_id": "VD1PIEBIIG", "menu_item_name": "Create Your Own", "modifiers": [ { "modifier_id ...

Creating a dedicated subfolder for 4 REST API routes for better organization

I'm struggling to figure out why my .get('/:post_id') route isn't working... My project's folder structure looks like this: app.js routes --api ----blog.js The blog.js file is located in the routes/api folder. In app.js, I&apo ...

How to access v-model from a separate component in Vue.js

How can I access a v-model that is located in a different component? The search field is within the App.vue file and I am trying to activate the :search='search' property in the Datatable.vue component. Code in App.vue: <v-text-field ...

Generating Unique Random DIV IDs with JavaScript

Does anyone know of a JavaScript solution to generate unique random DIV IDs? I am currently using PHP for this purpose. <?php function getRandomWord($len = 10) { $word = array_merge(range('a', 'z'), range('A', &apos ...

Is there a way to deactivate the <script> tag using CSS specifically for media queries?

When designing a website exclusively for desktop usage, I encountered the issue of it not being viewable on mobile devices. I attempted to address this problem by utilizing the code below: script { display: none; pointer-events: none; } Unfortunat ...

Tips for adjusting the position of rows within a v-data-table - moving them both up and down

Is there a way to rearrange rows up and down in the table? I've been using the checkbox feature and the CRUD data table from the documentation, but I haven't found any examples on how to implement row movement. Currently, my v-data-table setup l ...

The functionality of Bootstrap's Modal feature seems to be malfunctioning

I'm attempting to test the sample modals for my project, but even the codes from jfiddles are not working for me. When I click the button, it only gives me a dimmed window. I have also tried searching on Google for a solution, but to no avail. Below ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Combining numerous base64 decoded PDF files into a single PDF document with the help of ReactJS

I have a scenario where I receive multiple responses in the form of base64 encoded PDFs, which I need to decode and merge into one PDF file. Below is the code snippet for reference: var pdf_base1 = "data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KMSAwIG9 ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

Encountering an issue is common when trying to obtain a list of actors with a specific nationality like Argentine and sorting them by their full name

I am trying to filter actors by their nationality, specifically "Argentine", and sort them by fullName in ascending order. Below is my Actor Routes.js: router.get("/ask/actorsask", actorsCtrl.getActorByNationality); And this is my Actor controller.js e ...

Invoking middleware within another middleware

I was recently following along with a web development tutorial on YouTube where the instructor introduced two middlewares called verifyToken and verifyUser. `verifyToken` const verifyToken = (req, res, next) => { const token = req.cookies.access_token ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

The ion-input border seems to be fluctuating as the keyboard appears on the screen

I'm currently working with Ionic 3 and experiencing an issue where the selected ion-input's border in the ion-content is shifting when the device keyboard appears on the screen. Here is a visual representation of the problem: https://i.stack.imgu ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...