What is preventing me from using .bind(this) directly when declaring a function?

Consider the code snippet below:

function x() {

    this.abc = 1;

    function f1() {
       alert(this.abc);
    }.bind(this)

    var f2 = function b() {
       alert(this.abc);
    }.bind(this);
}

I am curious about how to make the "this" of the outer function accessible within functions f1 and f2.

Can anyone explain why VS2013 is flagging a syntax error with the bind(this) on function f1()? Thanks!

Answer №1

When it comes to function declaration statements and function instantiation expressions, there is a key difference. While both involve the use of the keyword function, a declaration statement cannot be directly used as a reference to a function. On the other hand, an instantiation expression is part of the expression grammar, allowing it to be freely used in that context as a reference to a function because that's what it ultimately evaluates to.

An example of this distinction can be seen here:

(function a() {

}).bind(this);

However, without utilizing the return value from .bind(), this construct may not serve much practical purpose.

In JavaScript, if the first token in a statement is function, then it signifies a function declaration statement. Conversely, if the initial token is something other than function, it could be another type of keyword-introduced statement (for, return, var, try, etc.), or an expression statement. In the case of an expression (or any expression within a different context), function instantiations function as part of the expression grammar and their value can be used as references to functions.


To simplify this concept further, let's imagine a scenario where the only way to instantiate a function in JavaScript is through a function expression. In other words, every use of the function keyword would create a function instance and return a reference to that function as its output.

Considering the nature of expressions and their role in computing values, when you require a specific value like 5 within an expression, you simply insert it and move on. For instance, merely stating 5; is a valid expression and does not result in a syntax error.

Similarly, in our hypothetical JavaScript world without function declaration statements,

function foo(a, b) {
  return a + b;
};

would essentially do nothing. The function would be created but immediately discarded since the reference to the instantiated function is not stored in a variable or utilized elsewhere. In such circumstances, you'd typically utilize

var foo = function(a, b) {
  return a + b;
};

as the preferred approach.

Despite these considerations, JavaScript does incorporate function declaration statements. By delineating a statement beginning with the keyword function as distinct from an expression statement containing a function instantiation, the language design allows for clearer differentiation between the two. Although alternative strategies could have been implemented (such as employing a different keyword), the potential for confusion remains.

Note that within the realm of JavaScript programming, some developers strongly advocate for using var declarations for functions, highlighting the subjective aspect of coding style preferences.

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

Choose the option for overseeing safaris

Hello there! I need some help with Safari. Can you please guide me on how to disable the arrows? https://i.stack.imgur.com/1gzat.png ...

Implementing a form submission using jQuery AJAX

Does this code look right to you? I am attempting to submit it and would like the text area to be empty again after submission. <script type="text/javascript"> $(document).ready(function(){ $("form#submit").submit(function() { // Store ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

Error code 405: The POST method is not compatible with submitting multiple forms using JavaScript code simultaneously

Having multiple forms on a single page that are all submitted using the same JavaScript code presents some challenges. <form class="form" id="cancelchallenge1" method="POST" action="{{action('ChallengeController@cancelChallenge')}}"> <i ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

Utilizing ng-repeat in a tabset to create an interactive and customizable tab interface

I am using angular ui tab (angular-ui.github.io/bootstrap/) and I expected that with ng-repeat, I would be able to make it dynamic, meaning the user can add tabs. However, unexpectedly it duplicates the tabs. Here is a demo: http://plnkr.co/edit/iHi1aOfbz ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

"Using Angular and TypeScript to dynamically show or hide tabs based on the selected language on a website

When switching the language on the website, I want to display or hide a specific tab. If the language is set to German, then show the tab; if any other language is selected, hide it. Here's my code: ngOnInit(): void { this.translate.onLangChange.s ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Guide to conditionally adding a property to an object in JavaScript

After scouring both Stack Overflow and Google for a solution, I finally stumbled upon this brilliant idea: x = { y: (conditionY? 5 : undefined), z: (conditionZ? 5 : undefined), w: (conditionW? 5 : undefined), v: (conditionV? 5 : undefined), u ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

Discover the power of integrating JSON and HTTP Request in the Play Framework

My aim is to develop a methodology that can effectively manage JSON and HTTP requests. This approach will facilitate the transition to creating both a Webapp and a Mobile App in the future, as JSON handling is crucial for processing requests across differe ...

Creating dynamic properties in JavaScript based on another object is a powerful way to manipulate data

In my current scenario, I am faced with the task of creating a new object named result based on an existing object called source. This new object must contain all properties from source, and also include additional "methods" named after the properties to ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

Step-by-step guide to adding products to your Supabase shopping cart

I have managed to insert a row into the "order" table with user information. Now, I want to individually add item details to a separate table named "order_storeItems" to create a relationship between the order and storeItems tables. I attempted using Pro ...