Tips for providing arguments in JavaScript

var Individual = { 
    name: "jana",
    retrieveName: function(cb) {
        cb();
        console.log("** "+this.name);
    }
}

var additionalIndividual = { name: "prabu"}

I possess 2 entities. I want to link "additionalIndividual" with the Individual entity and also pass a function as an argument.

I have attempted the following approaches, but they have not produced the desired outcome

Individual.retrieveName.apply(additionalIndividual, function(){})

Individual.retrieveName.apply(additionalIndividual)(function(){})

Answer №1

Utilize call to send a varying number of arguments to your function, or apply to send an array of arguments:

let Student = {
  name: "Sara",
  getGrade: function(callback) {
    callback();
    console.log("Grade: A");
  }
}

let anotherStudent = {
  name: "Tom"
}

Student.getGrade.call(anotherStudent, function () {})

Student.getGrade.apply(anotherStudent, [function () {}])

Answer №2

Have you experiment with Object.assign ? Try it this way

var Human = {
  desg: "vivek",
  getDesg: function(action) {
    action();
    console.log("** " + this.desg);
  }
}

var anotherHuman = {
  desg: "shilpa"
}
Object.assign(Human, anotherHuman).getDesg(alert)

Answer №3

One way to assign a value to the getName property is by using an arrow function that returns the name parameter.

var Person = {
  name: "jana",
  getName: (obj) => obj.name
}

var anotherPerson = {
  name: "prabu"
}

Person.getName(anotherPerson);
console.log(Person);

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 on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

AngularJS Bootstrap Datepicker populating date from input field

I'm currently utilizing Bootstrap for my web application. I've developed a method that initializes all input fields of type date with a class called form_datetime: function initDatepicker(){ $(".form_datetime").datepicker({ ...

Setting up internationalization (i18n) in JavaScript

I am in the process of creating a dynamic webpage using i18n's JavaScript library. I have been following their example code from their homepage located at: However, I am encountering difficulties in loading the specified JSON data, despite adhering t ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Utilizing EJS to display dynamic data from a JSON file in a visually appealing D

*Excited about learning express! Currently, I have two files - index.ejs and script.js. The script I've written successfully fetches JSON data from an api. const fetch = require("node-fetch"); const url = '...' fetch (url) .then(resp ...

Adjusting the orientation of a vector worldwide using a quaternion in THREE.js

Is there a way to set the absolute global rotation of a vector using a quaternion? Imagine a function called f(v, q) which rotates vector v to quaternion q. While THREE.Vector3 has a .applyQuaternion function for applying rotations to vectors, this is a ...

Difficulty displaying callback function within an object using Jquery for each

When iterating through a for-each loop in jQuery, I want to execute a callback function that is inside an object. Let's assume we have the following object: var myVar = { firstObj: { name: 'something' }, myFunc: function(value) ...

What is the best way to transform specific [x, y] coordinates into intervals of [xstart, xend, ystart, yend]?

In my project, I have the ability to draw tiles on an x-y grid and paint a provided png image. The objective is to then save these tiles as a .json file. Illustration of the issue: https://i.sstatic.net/XUfoS.png Currently, the JSON structure is created ...

How come the function String(value).replace(/[^0-9.-]/g, '') is effective?

I recently came across a function in a library that uses String(value).replace(/[^0-9.-]/g, '') to filter out illegal characters and return the legal number. I'm having trouble understanding how this works and what exactly gets replaced. At ...

Using event.target.value in find() caused the function to return undefined, but it worked as expected when storing the value in

I am facing a peculiar issue. I am working with a select component that passes a value called "classID" up to a useState. There is an array mapped over the select component which is sent from a NodeJS API and looks like this: [{classID: 371, teacherID: 1, ...

Techniques for implementing a PHP base_url() function in a JavaScript file

I need to pass base_url from the Book Controller to the book.js file This is the function within book.js function loadPage(page, pageElement) { // Create an image element var img = $('<img />'); img.mousedown(function(e) { ...

Ensure AngularJS ng-show and ng-hide are more secure

When using AngularJS, my goal is to conceal an element so that only authenticated users can access it. Although the ng-hide directive works, there is a vulnerability where someone could modify the class assigned to the element (ng-hide) using Developer To ...

Is it possible to delete a cookie using jQuery?

My DNN installation is experiencing an issue where one of the portals is broken and the "logout" button does not clear the cookie. I am wondering if there is a way to utilize jquery to specifically clear this cookie, or possibly create a separate ASP.NET ...

Customizing variables in webpack for production and development environments

Can a single variable be different in dev and production environments? How should I define this variable to handle the distinction? Is checking the location URL a suitable solution for achieving this? ...

searching for unspecified information in node.js mongodb

I am encountering an issue while trying to retrieve data from the database after a recent update. The code snippet result.ops is not functioning as expected in MongoDB version 3.0. I am receiving undefined in the console output. Can someone guide me on the ...

Troubleshooting Port Issue When Deploying Node/Sequelize Application on Heroku

I am in the process of developing a Node/Postgres application that will be deployed to Heroku. During my attempts to launch the app in a production environment, I encountered a timeout error. According to Heroku, this error is likely due to database or por ...

Enhancing user experience with autocomplete functionality using jQuery combined with server

Struggling with autocompleting a search field using jQuery-UI and encountering issues when trying to integrate PHP as the data source. The setup works smoothly with a variable as the source. JS: $(function () { var data = [ "ActionScript", ...

When clients format datetime, the default date value is sent on the form post

I'm attempting to utilize this particular example in order to correctly implement datetime formatting In my view model, I have a property for datetime public class MyViewModel { [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0 ...

No routes were found that match: ""

app.routes.ts import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PushComponent } from './push/push.component'; const appRoutes: Routes = [ { path: ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...