JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns an object, the instance variable becomes "undefined". Can anyone help me with this problem? (Check out a sample at http://jsfiddle.net/woko/vE4rq/2/ tested on recent versions of firefox & chrome)

function Funct() {
    this.varfunc = "this is an instance";
    return false;
}

var f = new Funct();
console.log(f.varfunc);

function FunctReturnobj() {
    this.varfunc = "this is an instance + returning an object";
    return {};
}

var fr = new FunctReturnobj();
console.log(fr.varfunc)

Answer №1

this within a function's scope refers to the DOMWindow.

this within an object's scope is actually referring to the object itself.

Answer №2

Utilizing constructors incorrectly can lead to unexpected results. Constructors should not have a return value. You can define methods for your object using the prototype property or within the constructor itself, as shown below:

function Constructor(value) {
  this.variable = value;
}

var obj = new Constructor('test');
obj.variable; // -> Returns 'test';

Similarly, you can create object methods like this:

function Constructor(value) {
  this.variable = value;

  this.say = function(something) {
    return "I say: " + something;
  };
}

Alternatively, you can use the prototype method:

function Constructor(value) {
  this.variable = value;
}

Constructor.prototype.say = function(something) {
  return "I say: " + something;
};

This is just a simple example, but it illustrates the concept effectively :)

Answer №3

Using the new operator results in a new object being created and the function applied to it - within the function scope, this refers to that specific object.

If the function is called without using new, or if there is a return statement present, it will not act as a "constructor". In such cases, this will point to the execution context, typically the window object.

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

How to achieve an endless cycle using Promise recursion in a NodeJS environment

I am planning to replace my blocking infinite while loop with promises. My run function is quite simple - it lights up an LED and then turns it off before moving on to the next one. Since Promises do not work inside while loops, I'm exploring how I c ...

What is the best method for setting a session cookie securely while also using CSRF tokens?

In my express application, I am working on setting the session cookie to be secure. Here is the code snippet I have tried so far: app.use(express.cookieParser()); sessionOptions = definitions.REDIS; sessionOptions.ttl = definitions.session.expiration; app ...

AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response? .controller('items_ctrl',['$scope','$http',function($scope,$http){ $scope.shop_id=localStorage.getItem(" ...

Retrieving the maximum values from JSON data using D3

Currently, I am working with D3 and JSON data by using a function that looks like this: d3.json("http://api.json", function(jsondata) { var data = jsondata.map(function(d) { return d.number; }); After executing this, the value of the data becomes ["2", ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

Incorporating '@vite-pwa/nuxt' into a nuxt 3 project leads to hydration issues

I have a Nuxt 3 website that I want to make PWA enabled. To achieve this, I am utilizing '@vite-pwa/nuxt'. However, after adding the package and enabling PWA in my nuxt.config.ts file, I encountered two issues: Hydration errors occur when refre ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

What are some strategies for handling data after it has been retrieved using Axios?

In my current project, I am working with MySQL database and fetching data using Axios and a useEffect hook. Once the data is retrieved, I pass it to a component as a prop. Here's how: const Component = () => { //Database URL const urlProxy = &q ...

Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the ...

Is it possible to reset the existing localStorage value if we access the same URL on a separate window?

In my app, there are two different user roles: admin and super admin. I am looking to create a new window with a Signup link specifically for registering admins from the super admin dashboard. Is it possible to achieve this functionality in that way? Cu ...

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...

terminate a node-cron task or abort a node-scheduler job

I'm currently working on a nodejs project that involves managing multiple cron jobs. However, I've encountered an issue when attempting to cancel these jobs. Here's the scenario: I have set up several cron jobs using node-cron or node-sch ...

Storing div content in database directly

I have a straightforward div that allows users to edit content on the page. I need to save this content in a database, but without including any HTML tags while still preserving line breaks. Currently, I am using the innerText property for this purpose. N ...

Concealing URL parameters in ui-sref (using ui.router)

Here is the HTML code I am working with: <a ui-sref="videoParent.Display.video({videoName:'[[sVid.slug]]', videoId:'[[sVid.videoID]]'})"><p>[[sVid.name]]</p></a> The parameters videoName and videoId are retriev ...

Tips on adding a base64 encoded image string to a JSON object using JavaScript

I'm trying to convert an image file into a JSON object using JavaScript. I've managed to turn the image into a string by utilizing base64 encoding, but I'm unsure how to then convert this string into a JSON object. Can anyone help? ...

Find the current location of the scroll bar on the view port

Currently, I am utilizing the Addazle React grid for my project. However, I need to incorporate endless scrolling functionality which is not already included in this grid system. Thus, I am tasked with devising my own solution for this issue. To successful ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

Encountering an "Angularjs 1.2.x Injector:modulerrr" error, even after successfully incorporating ngRoute

I am currently learning angularjs and I have encountered a persistent error. Despite multiple attempts at troubleshooting, I have been unable to resolve it. Here is the code that I have: index.html <!doctype html> <html ng-app="myApp"> <he ...