Здравствуйте. Объясните пожалуйста, почему редактор ругается на скрипт, который, в принципе, работает? Это проблема редактора или ошибка в коде? Как правильно делать, чтобы избежать такой ситуации? (листинг+скриншот ниже)
function insertRow(id) {
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row;
row = document.createElement("tr");
var cellCounter = document.getElementById("myTable").rows.length;
var td1 = document.createElement("td");
td1.appendChild(document.createTextNode(cellCounter));
var td2 = document.createElement("td");
var checkbox = document.createElement("input")
checkbox.setAttribute("type", "checkbox");
td2.appendChild(checkbox);
var td3 = document.createElement("td");
td3.appendChild(document.createTextNode(document.getElementById("add_id").value));
var td4 = document.createElement("td");
td4.appendChild(document.createTextNode(document.getElementById("quant_id").value));
var td5 = document.createElement("td");
td5.appendChild(document.createTextNode(document.getElementById("price_id").value));
var td6 = document.createElement("td");
td6.appendChild(document.createTextNode("action1"));
var td7 = document.createElement("td");
td7.appendChild(document.createTextNode("action2"));
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
row.appendChild(td7);
tbody.appendChild(row);
}
Файл .eslintrc:
{
"root": true,
"extends": "@ljharb",
"rules": {
"complexity": [2, 15],
"eqeqeq": [2, "allow-null"],
"func-name-matching": [1],
"max-depth": [1, 4],
"max-statements": [2, 26],
"no-extra-parens": [1],
"no-magic-numbers": [0],
"no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"],
"sort-keys": [0],
}
}
i update my brackets to version 1.11 , but it displays javascript errors without any reason like below screenshot. also «assigning a variable without using» is not a error is a WARNING! some of variables i defined in another js files , but brackets says ‘it is not defined’ !
Hi @salehmosleh,
consider adding a .eslintrc
file to your project for adjusting how ESLint
behaves. You can find the configuration options here: https://eslint.org/docs/user-guide/configuring.
For example for variables in different files, add them as globals either with
{
"globals": {
"var1": true,
"var2": true
}
}
or inline (top of the file) with
Hi @petetnt , thank you for your comment.
I think , brackets has to make and add .eslintrc file to my project by default configuration options at the first time. Not me! You know , it’s not fair , ‘mixed spaces and tabs’ is not an error even its not a warning. But brackets says ‘ERROR’. And many things like this …
I understand your frustration. As there’s as many possible combinations of options as there are projects, it’s not quite possible to create a one-size-fit-all configuration. However, there are many popular ones like https://www.npmjs.com/package/eslint-config-airbnb and https://www.npmjs.com/package/eslint-config-standard that aim to unify rules used into a common best practice set. Project that haven’t been coded against a linter before might be cumbersome to adapt into, but it also might be worth it. Remember that you can also start from just a few rules and turn on more if you want to in the future. Also did you know that you can fix many simple issues with Right Click -> Auto-fix with ESLint
? That would solve small issues like mixed tabs/spaces.
That said, you can also turn linting off altogether by setting linting.enabled
to false
in preferences (or Edit -> Lint files on save)
Is there any way to get something closer to sublime text’s default javascript linting? The linting by default is enough to make me not use Brackets, despite it being preferable for development in so many other ways. Maybe I’m just way too unfamiliar with js standards, but having it flag every single time I use console.log, and having to be sure to copy every single global variable and function into a linter file is annoying and makes the linting effectively useless because it crys wolf so much.
@whryan
Hi,
no idea how Sublime Text lints files by default, but .eslintrc.js
file is the de-facto way of configuring ESLint.
For example for disabling no-console
, you can use
module.exports = { rules: { "no-console": 0, ... other rules ... } }
Alternatively you can extend the recommended
config and disable the rules you don’t need (https://eslint.org/docs/rules/).
If you find linting distracting you can also disable it altogether from preferences.
See https://eslint.org/docs/user-guide/configuring for complete documentation.
Ah thank you! I should have looked for a manual more, really appreciate
that you linked this
…
Closing as answered, thanks!
How to use JavaScript in brackets text editor —
The behavior of the web pages can change by using the JavaScript language. The JavaScript language is the Script programming language or the Scripting language.
Coding JavaScript is easy in Adobe Brackets and is like coding HTML or CSS.
Brackets JavaScript Code Hinting –
In Brackets, the code hinting helps to avoid the physical typing of JavaScript. The code hints are helpful to provide suggestions for the required syntax.
The adobe brackets provide suggestions and code hints while typing the code.
JavaScript linting –
The JavaScript Linting tools are used to detect the bugs in the code. Sometimes simple mistakes might present in the code. These simple mistakes might be syntax errors, poor style of coding, spelling mistakes, wrong way of handling the errors, etc. By using the linting tools, these bugs are detected quickly.
There are some best linters to avoid these kinds of bugs. They are JSLint, JSHint, ESLint or JSCS.
Brackets JSLint Engine –
The JSLint Engine is the inbuilt linter in the Adobe brackets. In the JavaScript code, this lint shows the errors existing in the code. If the errors are present in the code, the JSLint will give the yellow symbol in the taskbar as a warning. If there are no errors, it shows the green mark.
Brackets JavaScript Errors – ESLint –
Using the ESLint, the Brackets editor will automatically detect the bugs in the JavaScript code if the linting option is enabled. This linting option will help detect the errors and gives immediate feedback.
The ESLint is better than the JSLint because the ESLint has better ES6 support, more flexible, clear, and crisp error messages.
How to disable Linting –
If there is a need to disable the linting option, click on the View menu and click on the Lint files on save.
View -> Lint files on save.
How do you run JavaScript code in Brackets console –
The console plus extension should be installed and then use the F9
shortcut key.
In the Brackets, this extension is used to see the console.log
and console.error
without using any developer tools.
From a live preview window, the user can filter the required logs by using this extension.
[Edited 2021-10-16 to reflect latest best-practices for producing RFC4122-complaint UUIDs]
Most readers here will want to use the uuid
module. It is well-tested and supported.
The crypto.randomUUID()
function is an emerging standard that is supported in Node.js
and an increasing number of browsers.
If neither of those work for you, there is this method (based on the original answer to this question):
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
console.log(uuidv4());
Note: The use of any UUID generator that relies on Math.random() is strongly discouraged (including snippets featured in previous versions of this answer) for reasons best-explained here. TL;DR: Math.random()-based solutions do not provide good uniqueness guarantees.
A closure is a pairing of:
- A function, and
- A reference to that function’s outer scope (lexical environment)
A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.
Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to «see» variables declared outside the function, regardless of when and where the function is called.
If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.
In the following code, inner
forms a closure with the lexical environment of the execution context created when foo
is invoked, closing over variable secret
:
function foo() {
const secret = Math.trunc(Math.random()*100)
return function inner() {
console.log(`The secret number is ${secret}.`)
}
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`
In other words: in JavaScript, functions carry a reference to a private «box of state», to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.
And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.
If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.
So, if you want a function to always have access to a private piece of state, you can use a closure.
…and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.
In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret
remains available to the function object inner
, after it has been returned from foo
.
Uses of Closures
Closures are useful whenever you need a private state associated with a function. This is a very common scenario — and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.
Private Instance Variables
In the following code, the function toString
closes over the details of the car.
function Car(manufacturer, model, year, color) {
return {
toString() {
return `${manufacturer} ${model} (${year}, ${color})`
}
}
}
const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver')
console.log(car.toString())
Functional Programming
In the following code, the function inner
closes over both fn
and args
.
function curry(fn) {
const args = []
return function inner(arg) {
if(args.length === fn.length) return fn(...args)
args.push(arg)
return inner
}
}
function add(a, b) {
return a + b
}
const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)()) // 5
Event-Oriented Programming
In the following code, function onClick
closes over variable BACKGROUND_COLOR
.
const $ = document.querySelector.bind(document)
const BACKGROUND_COLOR = 'rgba(200,200,242,1)'
function onClick() {
$('body').style.background = BACKGROUND_COLOR
}
$('button').addEventListener('click', onClick)
<button>Set background color</button>
Modularization
In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick
and toString
close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.
let namespace = {};
(function foo(n) {
let numbers = []
function format(n) {
return Math.trunc(n)
}
function tick() {
numbers.push(Math.random() * 100)
}
function toString() {
return numbers.map(format)
}
n.counter = {
tick,
toString
}
}(namespace))
const counter = namespace.counter
counter.tick()
counter.tick()
console.log(counter.toString())
Examples
Example 1
This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.
function foo() {
let x = 42
let inner = function() { console.log(x) }
x = x+1
return inner
}
var f = foo()
f() // logs 43
Example 2
In the following code, three methods log
, increment
, and update
all close over the same lexical environment.
And every time createObject
is called, a new execution context (stack frame) is created and a completely new variable x
, and a new set of functions (log
etc.) are created, that close over this new variable.
function createObject() {
let x = 42;
return {
log() { console.log(x) },
increment() { x++ },
update(value) { x = value }
}
}
const o = createObject()
o.increment()
o.log() // 43
o.update(5)
o.log() // 5
const p = createObject()
p.log() // 42
Example 3
If you are using variables declared using var
, be careful you understand which variable you are closing over. Variables declared using var
are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let
and const
.
In the following code, each time around the loop, a new function inner
is created, which closes over i
. But because var i
is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i
(3) is printed, three times.
function foo() {
var result = []
for (var i = 0; i < 3; i++) {
result.push(function inner() { console.log(i) } )
}
return result
}
const result = foo()
// The following will print `3`, three times...
for (var i = 0; i < 3; i++) {
result[i]()
}
Final points:
- Whenever a function is declared in JavaScript closure is created.
- Returning a
function
from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution. - Whenever you use
eval()
inside a function, a closure is used. The text youeval
can reference local variables of the function, and in the non-strict mode, you can even create new local variables by usingeval('var foo = …')
. - When you use
new Function(…)
(the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function. - A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
- A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
- A new set of local variables is created every time a function is called.
Links
- Douglas Crockford’s simulated private attributes and private methods for an object, using closures.
- A great explanation of how closures can cause memory leaks in IE if you are not careful.
- MDN documentation on JavaScript Closures.
I’m new to Ubuntu and I have this problem when I start an HTML file and then want to add a JavaScript script to it, Brackets shows errors even when everything is correct.
If I get the code and just insert it in the browser console it works but Brackets still shows its wrong.
kos
35.6k13 gold badges101 silver badges151 bronze badges
asked Mar 4, 2016 at 17:11
2
I have never used brackets, but what you are seeing is JSLint warnings — they are telling you is your coding style is not in agreement with JSLint. There must be preferences, or configuration somewhere that enables you to turn JSLint off.
Alternatively, you can engage in the exercise of following the warnings and cleaning up the code. You will learn to build your Javascript in a way that is more likely to make your teammates happy.
answered Mar 4, 2016 at 17:25
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.