Jquery code working fine until I included strict mode - javascript

A piece of Jquery Code was working just fine until "superiors" told me I must include strict mode on all my Javascript code. Everything is working fine on my main.js file except this piece of code. I can't reccon the error but my console error triggers every time i activate the script, it is a Boostrap 4 toggler button, it does open a menu, but the menu opens from up to bottom and really laggy. The button is supossed to collapse from right to left.
$(function(){
// mobile menu slide from the left
$('[data-toggle="collapse"]').on('click', function() {
$navMenuCont = $($(this).data('target'));
$navMenuCont.animate({'width':'toggle'}, 280);
});
})
Console error goes as follow:
Uncaught ReferenceError: $navMenuCont is not defined
at HTMLButtonElement.<anonymous> (main.js:61)
at HTMLButtonElement.dispatch (jquery-3.3.1.js:5183)
at HTMLButtonElement.elemData.handle (jquery-3.3.1.js:4991)

From the MDN reference:
First, strict mode makes it impossible to accidentally create global
variables. In normal JavaScript mistyping a variable in an assignment
creates a new property on the global object and continues to "work"
(although future failure is possible: likely, in modern JavaScript).
Assignments, which would accidentally create global variables, instead
throw an error in strict mode.
You need to declare your $navMenuCont variable.
For example:
var $navMenuCont = $($(this).data('target'));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Related

How to disable warnings about 'this' and strict mode using JSHint?

I am writing a web app using AngularJS (v1.5) so I have some controllers, and in those controllers I am often declaring something like :
function myController($someDirectives, ...){
var ctrl = this;
// My code
}
The thing is when I JSHint my code, I get this warning message for all of my 'this' declared in controllers :
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
I must precise that in my .jshintrc file, I set "strict":false.
Does anyone know how to disable this message in particular?
Thanks in advance.
set the configuration in .jshintrc file
{
"validthis": true // Tolerate using this in a non-constructor
}
You can always override jshint options in the code-block ie.
/* jshint validthis: true */
I had the same issue, with a very similar environment angular 1.5.5 always getting the same lint warning:
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
I've changed the name of my component's main function starting with upper-case and the warning disappeared
function MyController($someDirectives, ...){
I'm having the same issue. I'm doing "indirect invocation" with the function in question, not "function invocation", and 'this' is referenced many times in the function body.
In my case, I was having so many of these "errors" that jsHint quit before scanning my whole script.
To get around this I put this at the top of my script-file:
/*jshint maxerr: 10000 */
It did not suppress the errors, but at least it allowed me to scroll down to see jsHint's analysis of the entire script.

Why does prototyping Function not affect console.log?

I prototyped Function so that it has a getBody function:
Function.prototype.getBody = function() {
// Get content between first { and last }
var m = this.toString().match(/\{([\s\S]*)\}/m)[1];
// Strip comments
return m.replace(/^\s*\/\/.*$/mg,'');
};
See here for more info.
I tried to test it this way:
console.log(console.log.getBody.getBody());
but received an error: TypeError: console.log.getBody is undefined.
I figured out that maybe this happens because console.log was defined before I actually prototyped Function so I created an empty function x right before the prototyping and tried to call
console.log(x.getBody.getBody());
which worked without a problem. Checking the type of console.log with typeof console.log results in "function". Here's a CodePen to try it out. All of this wasn't really a surprise since it's what I expected except of console.log.getBody to be undefined.
So why does prototyping Function not affect console.log? I'm using Firefox 18.0.1 with Firebug 1.11.1.
This seems to be an issue with Firebug not with Firefox per se. My guess is that Function in Firebug lives in a different scope then Function in your page. (since unlike the other browsers Firebug is an extension , not a built in browser tool)
In fact if instead of Firebug you use the built in Firefox console (Ctrl+Shift+K), your code works perfectly fine.
More information about Firebug internals can be found here
http://getfirebug.com/wiki/index.php/Firebug_Internals
This excerpt may be interesting
When Firebug is detached from Firefox, open in a new or separate
window, the new window has its own scope. In that scope, a few Firebug
script tags compile to create a connection back to the original
browser.xul window. Most important, chrome.js is unique to each top
level window, but the Firebug object used by the detached window is
the object of the parent browser.xul.

Safari generates "Can't find variable" error although it is already defined in another Javascript page

The JavaScript script works with Chrome and Firefox but not in Safari. The code is:
$(document).ready(function(){
$(window).load(function() {
myVariable.start();
});
This generates:
ReferenceError: can't find variable: myVariable
The variable is defined in another JavaScript page that is included in this page, but for some reason Safari doesn't see the definition in the other page. Is Safari executing this script without loading the page that the variable is defined in?
How can I fix this?
Thanks for any help
Try to avoid setting global variables.
Maybe try assigning your variable to the window object, on top of the page:
window.myVariable = { start: function() {} };
Then when you need it:
$(window).load(function() {
window.myVariable.start();
});

javascript global variables visibility

I'm using a global variable in javascript, declared in a script tag outside any function:
<script type="text/javascript">
var prov_status_dict={};
....
</script>
Later on in a javascript method I'm using the variable normally.
temp=prov_status_dict[current_as_id];
I'm having issues with it on opera and ie, while on firefox it works. This is what opera's error console reports:
JavaScript - http://localhost:8000/input/
Event thread: click
Error:
name: ReferenceError
message: Statement on line 62: Undefined variable: prov_status_dict
stacktrace: n/a; see opera:config#UserPrefs|Exceptions Have Stacktrace
I've noticed that the problem is with global variables in general. I tryed moving some into hidden fields, but the same error pops up on the next use of a global var.
Help?
I usually access my globals through the window object so that I always have a point of reference
window.MyVariables = {};
window.MyVariables.prov_status_dict = {};
Give this a try, it might resolve your problem.
Try to avoid using global variables, see http://yuiblog.com/blog/2006/06/01/global-domination

variable assignments using jQuery failing in Safari?

I'm using jQuery 1.3.2 and it's breaking under Safari 4 for mysterious reasons.
All of my javascript references are made right before the tag, yet with the following code:
var status = $('#status');
status.change( function(){ /* ... */ } );
The following error is displayed in the Web Inspector:
TypeError: Result of expression 'status.change' [undefined] is not a function.
However the error is not encountered if I eliminate the variable assignment attach the change method directly like so:
$('#status').change( function(){ /* ... */ } );
Why? I need to use variables for this and several other findById references because they're used many times in the script and crawling the DOM for each element every time is regarded as bad practice. It shouldn't be failing to find the element, as the javascript is loaded after everything except and .
Try changing the variable to something other than "status."
It's confusing your variable with window.status (the status bar text). When I typed var status = $('#status') into the debugging console, the statusbar changed to [Object object]. Must be a bug in Safari.
If you put the code inside a function, so that status becomes a function-local variable, it should work.
It's standard practice in jQuery to wrap things in a
$.onready(function() {
});
This makes sure the DOM is loaded before you try to manipulate it.

Categories

Resources