the power of using keywords and prototypes

Greetings! I am currently delving into the realm of JavaScript, hailing from a C++ background. The transition has proven to be quite perplexing for me. Below is a snippet of code that I have been troubleshooting:

var someArray = [];
nameCompare = function(this.first,this.second) 
{
    if(first.name == second.name)
    {
        return 0;
    }
    else if(first.name < second.name)
    {
        return -1;
    }
    else
    {
        return 1;
    }
};

someArray.tempSort = function(){
    return this.sort(nameCompare);
};
var someOtherArray= Object.create(someArray);
someOtherArray.push({name: 'A', price: 3, rating: 2, distance: 2},
        {name: "B", price: 1, rating: 5, distance: 1},
        {name: 'C', price: 2, rating: 3, distance: 5},
        {name: 'D', price: 5, rating: 4, distance: 8});
console.log(someOtherArray.tempSort());

I find myself bewildered by the implementation of the 'this' keyword in this context. As someArray inherits properties from someOtherArray and I aim to sort based on name, I struggle with correctly referencing the name property from someOtherArray. While I grasped that the 'this' keyword points to the current object, my understanding still eludes me. Additionally, I continuously encounter an error pertaining to missing formal parameters. Is it not feasible to pass 'this.first' and 'this.second' through the auxiliary function?

Answer №1

To avoid errors, do not include this.x in your function parameters. Instead, pass variables (such as a and b) like this:

var someArray = [];
nameCompare = function (a, b) {
    if (a.name == b.name) {
        return 0;
    } else if (a.name < b.name) {
        return -1;
    } else {
        return 1;
    }
};

By including this in your function's parameters, you are encountering issues. Refer to MDN's explanation of the keyword for more details.

Answer №2

Check out this link for a working version of the code you were attempting: http://jsfiddle.net/TfM5U/

A couple of important points to keep in mind:

The line

nameCompare = function(this.first,this.second)
is creating a function and assigning it to the variable nameCompare. The names inside the parentheses are placeholders that can be used within the function, so there's no need for this. here.

Regarding this line:

var someOtherArray= Object.create(someArray);
. You can find more information about Object.create() at this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

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

Tips for extracting certain characters from a URL and saving them as an ID using JavaScript

Consider this scenario where I have a specific URL: http://localhost:3000/legone/survey/surveyform/form11/03141800300000030001 In order to achieve the desired outcome, I aim to extract and store different parts of the URL into designated IDs. Specificall ...

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

What is the best way to access the dimensions of a parent element in React with Hooks?

I am currently working on a new component and I am facing the challenge of obtaining the width and height of its parent <div>. Since all my components are functional ones using Hooks, the examples I found involving classes do not fit my case. Here i ...

Error message: Suitescript encountered an unexpected issue - TypeError: The function this.handleChange is not defined

For the past year, I have been immersed in Suitescript development. In my current project, I have a client script that triggers on Save for a Journal Entry. However, upon trying to save, I encounter an error message that reads "TypeError this.handleChang ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

Ways to switch classes within a loop of elements in vue.js

I'm just starting to learn vue.js and I'm working on a list of items: <div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvot ...

`Manipulating the image source attribute upon clicking`

I need help changing the attr: { src: ...} binding of an img element when a different image is clicked. Here is an example: $(document).ready(function () { var viewModel = { list: ko.observableArray(), showRenderTimes: ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

I'm experiencing an issue with my API where it is returning invalid JSON data when I make a POST request using

I have a scenario where I am making a post request to my Next.js API for updating an address. The code snippet below shows the function that handles fetching: async function handleSubmit() { const data = { deliveryAddress, landmark, pincode, district, bl ...

Chrome on IOS: Experiencing screen freezing while scrolling

1) I'm working with Material UI in React JS. I have added a simple scrollable code, but when I reach the bottom of the screen/scroll, it freezes. 2) I also tried it with a simple HTML page and it worked correctly. <div style={{ ...

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Attempting to incorporate country flags into the Currency Converter feature

www.womenpalace.com hello :) i'm looking to customize my Currency Converter with Flags images. this is the code for the converter: <select id ="currencies" class="currencies" name="currencies" data-default-shop-currency="{{ shop.currency }}" ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

How can you disable an 'option' HTML5 element using the AngularJS methodology?

How can I disable an 'option' element in HTML5 using AngularJS? Currently, I am working with AngularJS v1.2.25. Here is the Plunk Link for reference: https://plnkr.co/edit/fS1uKZ <!-- CODE BEGIN --> <!DOCTYPE html> <html> ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Is it feasible to pre-load external websites using JavaScript?

While searching on various platforms, including Stack Overflow, I couldn't find a solution to this specific query. I'm not necessarily seeking an implementation already in place, but rather ... Imagine having an intranet application that loads q ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...