Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below.

let f = { 
    a: 3, 
    printMyBrother() { console.log(X) } 
}.printMyBrother

f()

To programmatically log "3" on the console using the above code, what should be replaced by X?

Answer №1

If you tweak your code a bit, you can achieve this:

Here are various methods that demonstrate how this concept works. The functionality is dependent on the unique rules of javascript's this.

let f = {
  a: 3,
  printMyBrother(message) {
    console.log(message, this.a)
  }
}
let printMyBrother = f.printMyBrother;


console.group('function');
console.log('function');
f.printMyBrother('function call')

// The printMyBrother won't work alone without being bound
printMyBrother('unbound function call');

// Bind printMyBrother variable to always refer to f
printMyBrother = printMyBrother.bind(f);
printMyBrother('bound function call')
console.groupEnd();


class ClassF {
  a = 3;
  // This is unbound to the class by default
  // because it's not an arrow function
  // You can bind it in the constructor manually, however
  printMyBrotherUnbound(message) {
    console.log('classF', message, this.a)
  };
  // This is bound to the class by default
  // because it's an arrow function
  // This should work in all major browsers (besides IE)
  printMyBrotherBound = (message) => {
    console.log('classF', message, this.a)
  }
}


let classF = new ClassF();
console.group('Class Method')
console.log('Class Method')
printMyBrother = classF.printMyBrotherUnbound;
classF.printMyBrotherUnbound('in class');
try {
  printMyBrother('unbound');
} catch (error) {
  console.log('unbound class function errors out because this is undefined');
}
console.groupEnd()

console.group('Class Arrow Function');
console.log('Class Arrow Function');
printMyBrother = classF.printMyBrotherBound;
classF.printMyBrotherBound('arrow function');
printMyBrother('unbound arrow function');
console.groupEnd();

For more information about the this keyword in JavaScript, check out these resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

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

Prevent side-to-side scrolling on elements that exceed the width of the screen

I am working on building a navigation system similar to Google Play, where there are fixed tabs for browsing through the app. I have created a container div that holds various content sections. <div id="container"> <div class="section"> .. ...

Why is this tetris piece not appearing fully on the grid when using arrays?

Below is the code snippet, and you can find a link to the jsfiddle below. I'm facing an issue where the first row of the block is not being drawn, and dealing with these 2-dimensional loops is quite challenging for me. I am unable to figure out why t ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

Numerous perspectives within an angular.js application

Issue I'm currently working on creating a product list with the following initial features: Server-side pagination Server-side filtering I am facing several challenges with my current setup, but the main issue is that I can't figure out how to ...

Enhancing Luxon DateTime with extension type support

Referencing the issue at https://github.com/moment/luxon/issues/260, I am looking to extend the DateTime object as shown below: import { DateTime } from 'luxon'; function fromUnix(tsp?: number): DateTime { return DateTime.fromMillis(tsp * 1000 ...

Display a message to a user on the same HTML page using jQuery or JavaScript

How can I show a message to the user on the HTML page confirming their selected date without using an alert box? I attempted this code snippet, but I'm uncertain: document.writeln("The date you picked is: " + dateText); ...

Issue when transmitting information from Angular to Express

I'm attempting to send data from Angular to Express.js Below is my TypeScript function connected to the button: upload(): void { const nameFromId = document.getElementById('taskName') as HTMLInputElement; this.taskName = nameFromI ...

Generate a JavaScript function on the fly

I am looking for a way to dynamically bind a function to the .click() event of multiple divs in a loop. Once clicked, the function should hide the respective div. Despite my attempts, I have been struggling with losing reference to the div and unsuccessful ...

Steps for organizing an array based on unique requirements

My goal is to retrieve an array that consists of the first and second objects based on the "point" property of each object I have a specific condition where if it is satisfied, the positions will be swapped. Default: ENGLISH[0] ENGLISH[1] MATH[0] MATH[1] ...

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

Convert JavaBeans sources into a JSON descriptor

I'm in search of a tool or method to analyze standard JavaBeans source code (featuring getters and setters) and create json descriptors using tools like grunt or ant, or any other suitable option. Here's an example: FilterBean.java: package com ...

Leverage the camera functionality in both native and web applications using Ionic/AngularJS and Cordova

Could you provide some guidance on how to use the Camera feature in both web and native environments? I have tried implementing it using the code snippet below, taken from ng-cordova documentation: $scope.takePicture = function() { var options ...

Dealing with undefined URL errors

My frontend log is crowded with these errors. Whenever I visit an undefined address, my terminal in VSCode displays the following error messages. The real issue is that I am unsure how to effectively manage errors arising from hitting an undefined URL. For ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Using jQuery Mobile: Implementing listview data-filter for multiple data sets

I'm working on a JQM page with two data-role="listview" elements. Both of them are using the same data set, but one listview displays only text while the other includes icons as well. My goal is to implement the data-filter="true" option for both lis ...

Using the append() method in d3 with a function argument adds new

This is functional code: // A d3.select("body").selectAll(".testDiv") .data(["div1", "div2", "div3"]) .enter().append("div") .classed("testDiv", true) .text(function(d) { return d; }); The next snippet is essentially the same, except that ins ...

What is preventing me from using AJAX to input data into sqlite?

Implementing a local save feature in my Web App is proving to be quite challenging. Every time I attempt to send data in any form, I consistently encounter the following error: A builtins.TypeError occurs, followed by a stack trace in /SaveFile and jquery ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...