What is the reason behind JSHINT flagging this as a strict violation?

I suspect that this could potentially be a duplicate of Strict Violation using the keyword 'this' and the revealing module pattern

Here is the code snippet in question:

function navigateToPage(s){
    if(s<=this.d&&s>0){this.g=s; this.page((s-1)*this.p.size);}
}

function pageTransition(event, sorter) {
    var dd = event.currentTarget;
    navigateToPage.call(sorter, dd[dd.selectedIndex].value);
}

Despite my efforts, JSHINT (or JSLINT) seems to have an issue with it. It specifically highlights "Strict violation." for the marked line.

Do you think utilizing Function.call() followed by referencing the instance is not appropriate in this case?

Could this be viewed as poor coding etiquette?

Answer №1

According to JSHint, a "Possible strict violation" is flagged when you use this within something that appears not to be a method.

In non-strict mode, using gotoPage(5) would bind this to the global object (window in the browser). However, in strict mode, this would be undefined, leading to potential issues.

To ensure intended functionality with a specified this context, consider utilizing methods such as gotoPage.bind(myObj)(5) or gotoPage.call(myObj, 5). By doing so, any JSHint errors can be disregarded. Nevertheless, the use of this in a non-method context can be confusing for others reviewing your code. A clearer approach would be to pass the object as an argument:

function gotoPage(sorter, s) {
    if (s <= sorter.d && s > 0) {
        sorter.g = s;

        sorter.page((s - 1) * sorter.p.size);
    }
}

function pageChange(event, sorter) {
    var dd = event.currentTarget;
    gotoPage(sorter, dd[dd.selectedIndex].value);
}

Answer №2

I once encountered a situation where a message was not capitalized at the beginning of a function.

"use strict";

// ---> violation of strict mode
function example() {
    this.testing = "";
}


// ---> no issues (pay attention to the capital E in Example)
function Example() {
    this.testing = "";
}

Answer №3

When defining a function as a variable rather than using the standard function declaration, jshint will not identify it as a strict violation. To demonstrate this behavior, you can follow these steps:

var changePage = function (pageNum){
    if(pageNum<=this.totalPages && pageNum>0){this.currentPage=pageNum; this.displayPage((pageNum-1)*this.pageSize);}
};


var selectPage = function (event, sorter) {
    var dropdown = event.currentTarget;
    changePage.call(sorter, dropdown[dropdown.selectedIndex].value);
};

Answer №4

When attempting to incorporate a method, consider assigning it to the prototype like this:

SampleClass.prototype.moveToPage = function moveToPage(page){
  // implementation code here
};

JSHint will not issue any warnings when assigning the function.

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

Refreshing a page occurs every 30 seconds or upon the user submitting a form

My PHP page consists of various includes for different sections of a video website. One of these sections is a comments area where users can submit their feedback to a database successfully. However, I want to ensure that only the specific included page/di ...

Selecting elements with special characters in their IDs using JQuery can be done

I am facing an issue with this HTML code where the Id includes special characters: <input type="text" id="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d ...

Issues encountered with AES decryption when utilizing CryptoJS

Currently, I am facing an issue with encrypting and decrypting data using AES encryption. In my code, I am encrypting the data in javascript using crypto.js and trying to decrypt it in Java. Encryption and decryption work correctly when done in either jav ...

Error encountered in React while using an object in useState: TypeError - Unable to access property 'name' of undefined

Encountering an issue with receiving JSON data from a route. When logging the data, it shows up correctly. However, when passing it to setProfileData(data), the updated state becomes undefined. Interestingly, when using setProfileData(data.user.name), it ...

Organizing data in a table with AngularJS

I have recently started learning AngularJS and am currently working on sorting my table by clicking on the table headers. When a header is clicked, I want the rows to be sorted based on that specific header. If you'd like to see my code in action, he ...

Encountering an Issue: Unable to Generate Line Chart with gRaphael Library

I'm currently working with the gRaphael JavaScript library to create a basic line graph. Here is the code I have implemented on my page: <script language="javascript" type="text/javascript"> var paper = Raphael(10, 50, 640, 480); paper.g.line ...

Unable to control the content within the Repeater DIV

When working inside a repeater's ItemTemplate, I encountered an issue where only the first image/div toggled visibility when the toggle button/link was pressed. The images are dynamically loaded from the database and the toggle function seems to only ...

The state is not updating in a timely manner

After clicking submit in the form, I only receive results upon a second press. When debugging, it appears that setState is updating the state only on the second attempt (userId), but I want it to wait until the state is fully updated (so userId will refl ...

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

Using app.get('env') in local development and live production settings

var express = require('express'); var app = express(); var db_url; if(app.get('env') == "development"){ db_url = 'mongodb://127.0.0.1:27017/localhost'; }else{ db_url = 'something else'; } console.log(app.get(&apos ...

What could be causing the Ajax error to occur in my .Net Data table?

While trying to load a table, I encountered an ajax error in the datatable (.net). Below is the code for my data table: <table id="productsTable" class="table table-striped table-bordered"> <thead> <tr> <th>Name</th ...

Having trouble setting up email with Passport-local. Any new suggestions?

I have been working on implementing user log-in using passport-local and express. While I have successfully managed to achieve log-ins with usernames, I find them hard to remember and not ideal for user authentication. Therefore, I attempted to customize t ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

What is the best method to determine if a Django object is null in JavaScript?

Is there a way to verify if a Django object is null in JavaScript? At this moment, I have a variable called person which can hold a Django object or null. In my JavaScript code, I am using: if ({{person}} != null) { execute_function({{person}}) } Ca ...

Creating an intricate table layout using AngularJS and the ngRepeat directive

I'm attempting to create a table similar to the one shown in the image below using HTML5. https://i.sstatic.net/DiPaa.png In this table, there is a multi-dimensional matrix with Class A and Class B highlighted in yellow. Each class has three modes ( ...

Filter your DataTables columns by searching for text within a specific range

Below is the code for implementing a text range filter in SQL: function fnCreateTextRangeInput(oTable) { //var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; th.html(_fnRangeLabelPart(0)); var sFromId = oTable. ...

Difficulty with AngularJs Translation Partials

I have encountered an issue with binding translation. Some objects are converting to their translated value successfully, while others, as mentioned below, are not working. This problem only occurs the first time I build the project. Upon refreshing, every ...