The impact of returning a JSON object in a Javascript constructor

When it comes to using a JavaScript constructor to return a JavaScript object literal or simply setting properties with this.XYZ, are there any performance or functional differences? Consider the following example:

    function PersonA(fname, lname) {
        this.fname = fname;
        this.lname = lname;
    }

    function PersonB(fname, lname) {
        return {
            "fname": fname,
            "lname": lname
        };
    }

Both options appear to behave appropriately:

    PersonA.prototype.fullName = function() { return this.fname + " " + this.lname; };
    PersonB.prototype.fullName = function() { return this.fname + " " + this.lname; };

    var pA = new PersonA("Bob", "Smith");
    var pB = new PersonB("James", "Smith");

    alert(pA.fullName());
    alert(pB.fullName());

Is one approach preferable for any specific reason, or is it purely a matter of personal preference? If just a matter of preference, is one considered more standard than the other?

Answer №1

They are not completely identical.

When you return the object created from the constructor...

  • it will inherit from the prototype of the constructor
  • it will have the instanceof operator available to test which constructor created it

The reason why the fullName() method appears to work for pB is because both instances were created using the PersonA constructor.

var pA = new PersonA("Bob", "Smith");   // uses PersonA constructor
var pB = new PersonA("James", "Smith"); // uses PersonA constructor???

Just an FYI, it's called a "JavaScript object literal", not a "JSON object literal".


EDIT: You have now updated the code in the question to use the PersonB constructor. Give it a run again, and you'll notice an Error in the console.

Answer №2

Every time a function constructor is invoked, it initializes an empty object which is then referred to as 'this' within the function constructor.

Consider the example of PersonA:

// initialize an empty object
var emptyObj = {}; 

// invoke the function with the empty object as context
PersonA.call(emptyObj, "Bob", "Smith");

This code results in emptyObj having the following properties:

{
   fname : "Bob",
   lname : "Smith"
}

When PersonB is called, a similar process occurs where a new empty object is created using new, but this time a different object is returned instead of doing anything with the empty 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

Can an element be targeted for hover in CSS without it being a child element?

In my HTML code, I have an <aside> and a <header>. The <header> contains a child element called container, which has some children including one named burger bar. What I am trying to achieve is that when I hover over the burger bar elemen ...

Converting JSON data into a deeply nested Ruby hash

I have a JSON block that needs to be converted into a ruby hash for easier data manipulation. json_blob = {"SOMETHING"=>{"FOO"=>"BAR", "DOG"=>"NIGHT}} This conversion will allow me to quickly access and verify the presence of specific data withi ...

The visual representation is not being generated (three.js)

I recently designed a basic scene in three.js, however I am facing an issue where it does not seem to work with the canvas renderer, even though it should work correctly. Here is the code: http://jsfiddle.net/PRkcJ/ The scene only functions properly when ...

display images fetched from a PHP/MySQL database in a jQuery dialog box

UPDATE: A solution has been found and the code has been updated accordingly. Currently, I have the images stored in a directory on my local system where I am hosting an IIS server. I am able to retrieve these images successfully and display them using the ...

Convert an array into a query string parameter

Currently, I am refactoring some code and attempting to replace the generation of query strings through concatenation with serializing a JSON object. Original Code: $.ajax({ url:'./services/DataService/getDetails?metric=9&'+dashBoards.g ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

Only allow the next button to navigate to another tab if the JSON response is verified as true

This particular HTML form entails a tab-pane with specific data and inputs to be filled out. <div class="tab-pane" id="step1"> <form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmi ...

What is the best way to deserialize a collection of enum values with Jackson JSON?

Currently, I am developing a configuration system where I aim to load config values from a JSON file and have them automatically converted into the required Java type. My choice for JSON parsing is Jackson, which works well with primitive types like floats ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

I'm having trouble getting jquery css to function properly in my situation

I am trying to implement a fallback for the use of calc() in my CSS using jQuery CSS: width: calc(100% - 90px); However, when I tried running the code below, it seems like the second css() function is not executing. I suspect that there might be an issu ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

"Utilize Google Sheets to extract and monitor Best Buy prices through web scraping

Looking to automate the process of scraping product prices into Google Sheets. Previously used =importrange(A1,B1) A1 = B1 = /html/body/div[3]/main/div[2]/div/div[1]/div[3]/div[2]/div/div[1]/div[1]/div/div/div/div/div/div/div[2]/div[1]/div[1]/div/span[1] ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Retrieve the chosen option index using AngularJS

It is common knowledge that a select list can have multiple options, each starting from [0]. For example: [0]<option>E.U</option> [1]<option>India</option> [2]<option>Peru</option> In my Angular application, I am using ...

Using jQuery to target the element before

Is there a way to determine the width of elements located before an element when it is hovered over? I attempted to achieve this using the following code: $('ul li').hover(function() { $(this).prevAll().each(function() { var margin = $(this ...

"Utilizing AngulaJS to apply a class to the parent element when a radio button is

I'm wondering how I can assign a class to the parent div of each radio button in a group? You can find the code below and view the corresponding JSFiddle here. Here is the HTML: <div class="bd"> <input type="radio" ng-model="value" val ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

What is the method to track the number of tspan elements within each span element?

How can I use jQuery to count the tspan elements inside multiple span elements within svg text? var count_tspan = jQuery('span text').children().length; // 4 console.log(count_tspan); <div class="content-inner"> <span id="item-0" cl ...

Tips for determining the actions of a node prior to its inception

Is there a way to automatically run scripts on specific elements after their creation? For example, using a jQuery plugin like autoresize to expand the height of a textarea. If I use $('.textarea').autosize(), only the current textareas will be a ...