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

What is the best way to save the data received from createApi into the Redux store?

Currently, I am faced with the challenge of storing user data (such as name, email, etc.) obtained through the createApi function into Redux store. However, I'm unsure of the best practice to achieve this. In my userApi.js file: export const userApi ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Issue: The key length and initialization vector length are incorrect when using the AES-256-CBC encryption algorithm

Within my coding project, I have developed two essential functions that utilize the AES-256-CBC encryption and decryption algorithm: import * as crypto from "crypto"; export const encrypt = (text: string, key: string, iv: string) => { con ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

RxJS BehaviorSubject allows you to retrieve the current value or obtain a new one depending on a specific condition

I am managing a subject that consumers subscribe to: private request$: Subject<Service> = new BehaviorSubject(null); Upon initialization, my components utilize this function: public service(id: number): Observable<Service> { return this. ...

Initializing Angular variables

My Angular controller has a variable called $scope.abc. The backend I'm using is Sails. The initial value of $scope.abc can be set by the backend when the page is first generated. Once the page is displayed, the user may or may not change this value ...

Node.js and Express: Delegate routes to different endpoints for handling by the Single Page Application, instead of just the root route

I have my node.js/Express server configured to host my Vue.js single page application from the root URL path (localhost:3333) within the public folder. When navigating through my app, everything works smoothly thanks to the vue.js History API handling all ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

The requested function is nowhere to be found within the confines of my Controller module

While working on a personal project, I encountered an issue where a function from another class in a separate Java file is not being found, even though it is defined in the respective class. EventView.js: displayEvent(event){ this.EventTitle = event. ...

Unable to suppress error in AngularJS $http.get() call when using catch() method

Below is a simplified version of the code I'm working with, running in CodePen for example: var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("https://codepen.io/anon/pen/L ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...

Ways to reload the page following the submission of a form

I implemented a fade dialog to present a form, and successfully submitted the form using ajax to create a new record in the database. Now, I am facing an issue where I cannot refresh the page after the ajax call finishes. Despite attempting to use JavaScr ...

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...