Can someone explain this unfamiliar JavaScript array notation?

I've been struggling to find an answer on Google and Stack Overflow for the purpose of this JavaScript code snippet:

obj['e'+type+fn]( window.event );

My interpretation is that it resembles accessing a specific array element with an argument:

array[index](argument);

However, my understanding is limited. Could this possibly be similar to:

array[index]=argument

This would mean assigning an argument to an element in an array.

If anyone can provide a simple example illustrating what this code snippet does, I would greatly appreciate it. I'm trying to dissect John Resig's addEvent() implementation. Rather than detailed explanations or examples related to that, I'm looking for something more basic like MDC's explanatory approach for call method, which uses fictional products as examples.

Answer №1

obj['e'+type+fn]( window.event );

This code snippet demonstrates a method of accessing properties within an object dynamically by building the key from multiple strings. For example, given an object:

a = {
 name: 'someName',
 age: 20
};

You can access the property "name" by using a.name, or alternatively a['name'].

The developer uses the bracket notation [] to construct the key based on values stored in variables. So, if type=click and fn=foo, he is accessing obj.eclickfoo or obj['eclickfoo'].

The accessed property must be a method since it is being invoked with (); therefore, he essentially executes:

obj.eclickfoo( window.event );

or in another equivalent form:

obj['eclickfoo']( window.event );

Answer №2

Here is the breakdown of its functionality:

It retrieves the function from the array obj using the index 'e'+type+fn. This function is then executed with window.event passed in as a parameter.

Keep in mind that using () will call a function, while using [] will retrieve a value from an array.

Answer №3

fetching the function by using obj['e'+type+fn]
will result in obtaining a function type, which is subsequently run with window.event as an argument.

Answer №4

obj['e'+type+fn]( window.event );

The use of the "obj[...]" notation is not limited to arrays in JavaScript; it can be applied to any object as well. In this particular case, Resig is adding a property to various objects, specifically targeting DOM objects.

Using obj['aVar'] is essentially the same as using obj.aVar, but with added flexibility. The former allows for the handling of reserved keywords and dynamic access to property names, such as demonstrated with the type variable example. Trying to access obj.type directly wouldn't yield the desired result because it would search for a property named exactly "type," rather than one matching the value of the type variable.

Objects and arrays can store functions as data, enabling the invocation of a function within an object or array by specifying its property followed by parentheses (as shown here) with arguments like window.event. Additionally, functions have a default toString method on their prototype, helpful for cases requiring string concatenation while maintaining function integrity unless the user specifies a custom toString method on the function itself.

Resig's approach involves defining a new property somewhat haphazardly, but implemented in a way that minimizes potential conflicts with other applications. For instance, assigning the values "click" to the type variable and function () {alert('boo!');} to fn results in naming a property on document.body identified as "eloadfunction () {alert('boo!');}". By creating and invoking this property within his anonymous function, Resig ensures consistent behavior when utilizing the "this" keyword—it defaults to referencing the parent object (obj), avoiding global references unless obj represents the global context (i.e., 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

Tips for simulating a decorator function applied to a method used in the system under test using JEST

I currently have a typescript class setup like this: export class SystemUnderTest { @LogThisAction('something was done') public doSomething() {} } It is clear that reflection is being used to execute a specific decoration function: exp ...

Detecting collisions between multiple moving objects in Three.js

Currently, I have several objects that are moving forward randomly using the following code: model.lookAt(position_x, 0, position_z); setInterval(function(){ model.translateZ(0.015); }, 10); However, I am facing an issue where these objects might cras ...

Real-time chart updates through REST API integration with JavaScript

I am searching for a JavaScript library that is capable of creating line charts and making calls to a REST API every few seconds (such as 5s or 3s) in order to update the line chart dynamically. I have found some libraries that support live chart updatin ...

What is the most effective method for enlarging elements using Javascript?

I have come across many different methods for expanding elements on webpages, such as using divs with javascript and jquery. I am curious to know what the most optimal and user-friendly approach is in terms of performance, among other things. For instance ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

Exploring the contents of a text file using JavaScript

Trying to wrap my head around this. It seems like the usernames are working fine, but not the passwords. I'm extracting data from a text file with the structure "username,password". John,BOL12345 Mary2,BOL77777 Anna,BOL54321 test,BOL12345 The fi ...

JavaScript loaded only on first visit or after the page is refreshed

For my cross-platform app using Cordova and jQuery Mobile 1.4.5, I have a basic html page that needs to load a javascript file. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Security-Policy" content="default-src ...

Tips for distinguishing between local and remote variables (PHPStorm, Webstorm)

Is there a way to create a dynamic variable within my project that can be accessed in both JavaScript and PHP, which will automatically populate based on settings in WebStorm before deployment (locally or remotely)? For instance, let's say I define th ...

using a variable object to load, access data, and handle errors through mutations

element, I have incorporated two distinct mutations in a single react component: const [get_items, { error, loading, data }] = useMutation(GET_ITEMS); const [add_to_cart] = useMutation(ADD_TO_CART); To streamline and access both components' error, ...

Incorporate a class into the fixed navigation menu using fullpage.js

I am attempting to modify the behavior of a sticky menu as the user scrolls down using fullpage.js. My goal is to have the #top-wrapper behave normally when the first section/page loads, and then add a class of is-fixed as you scroll down. When scrolling ...

Incorporating JavaScript into a pre-existing HTML and CSS user interface

After successfully coding a chat app UI for my project site using CSS and HTML, I am now facing the challenge of adding functionality to my existing code. The issue is setting up the client server and integrating chatting functions into my current UI. Mo ...

Retrieving the identifier from a value within a Symfony controller

One thing I am looking to achieve is to retrieve an Id based on a folder number. Both the Id and folder number (which is unique) are located in the same controller. I input the folder number from a text box and then need to direct the user to a /Id page. ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

No content visible at the top of the browser window on HTC Android (4.0.3) due to white space

We are currently developing a mobile web application with specific features. Our app contains a fixed header at the top of the page using position:absolute and top:0px, along with scrollable content below it. Additionally, there is a text area within the ...

Event Triggered Upon Element Addition to DOM: JQuery Livequery Equivalent in Version 1.7

Is it possible to trigger an event when a certain element is added to a page, especially when I am using a Chrome extension and do not control the source page? I have explored the capabilities of JQuery 1.7's on() method, but it seems to focus on spe ...

Struggling to compare array elements with input value and receiving a false result using jQuery

I have been attempting to compare an array list of numbers to an input number value, but each time the loop runs, it fails to find a match. The requirement is that if the value of input2 matches any of the values in input1, it should display the alerts in ...

What could be causing the getTotals() method to malfunction?

I have been working on a finance app that is designed to update the "income", "expenses", and "balance" tables at the top each time a new item is added by the user. However, the current code seems to be failing in updating these values correctly based on u ...

Is there a way to continuously iterate this PL/SQL statement in order to display numerous markers on my Google map?

In my current project, I am utilizing an Oracle 12c database, APEX 5, and the Google Maps API. What I am trying to achieve is plotting the coordinates of each sighting from the sighting table onto the map. To accomplish this, I prepare the map before ente ...

What is the most effective method for regularly updating single page applications using PHP/HHVM as the backend?

While working on my single page application using AngularJS, I have come to appreciate the efficiency of creating web applications in this way. My backend language is PHP and the service functions as a REST"ish" API. However, I am currently facing an issu ...