"엄격 모드"란 무엇이며 어떻게 사용됩니까?
Mozilla Developer Network에서 JavaScript 참조를 살펴본 결과라는 것을 발견했습니다 "strict mode"
. 나는 그것을 읽고 그것을 이해하는 데 어려움을 겪고 있습니다. 누군가가 일반적으로 그 목적이 무엇이며 어떻게 유용한 지 간략하게 설명 할 수 있습니까?
주요 목적은 더 많은 검사를 수행하는 것입니다.
"use strict";
다른 코드보다 먼저 코드 상단에 추가 하십시오.
예를 들어 blah = 33;
유효한 JavaScript입니다. 그것은 당신이 완전히 전역 변수를 만들 것을 의미합니다 blah
.
그러나 엄격 모드에서는 키워드 "var"을 사용하여 변수를 선언하지 않았으므로 오류가 발생합니다.
대부분의 경우 임의의 범위의 중간에 전역 변수를 만드는 것은 아닙니다. 그래서 blah = 33
작성된 대부분의 시간 은 오류이며 프로그래머는 실제로 전역 변수가되기를 원하지 않았습니다. 쓸 수 var blah = 33
있습니다.
마찬가지로 기술적으로 유효한 많은 작업을 허용하지 않습니다. NaN = "lol"
오류가 발생하지 않습니다. 또한 NaN의 값을 변경하지 않습니다. 엄격한 이것을 사용하면 (그리고 비슷한 이상한 문장) 오류가 발생합니다. 글을 쓸 이유가 없기 때문에 대부분의 사람들은 이것을 높이 평가하므로 NaN = "lol"
오타가있을 가능성이 높습니다.
Simon의 답변에서 아직 언급되지 않은 엄격 모드의 한 가지 측면은 함수 호출을 통해 호출 된 함수에서 엄격 모드가 설정 this
된다는 것 undefined
입니다.
그래서 이런 것들
function Obj() {
this.a = 12;
this.b = "a";
this.privilegedMethod = function () {
this.a++;
privateMethod();
};
function privateMethod() {
this.b = "foo";
}
}
불필요 하게 전역 객체에 속성을 추가하는 대신에 privateMethod
속성을 추가 할 수 없으므로 호출 될 때 오류가 발생 합니다.undefined
b
엄격하게 분석 할 수있는 EcmaScript의 하위 집합이있을 수 있도록 엄격한 모드가 추가되어 이후 버전의 언어에 적합합니다. 엄격한 모드는 또한 엄격한 모드로 자신을 제한하는 개발자가 실수를 줄이고 버그를보다 분명하게 나타낼 수 있도록하기 위해 고안되었습니다.
E5aScript의 차기 주요 버전이 될 하모니 는 ES5 엄격 위에 구축 될 것입니다.
하모니는 너무 많은 모드를 피하기 위해 ES5 엄격 모드를 기반으로합니다.
다른 언어 실험도 엄격 모드에 의존합니다. SES 는 ES5 엄격 모드의 분석 가능성에 따라 다릅니다.
SES (Secure ECMAScript) 설계 실험
ES5 / Strict의 기능을 제거하거나 복구하여 객체 기능 프로그래밍 언어를 설계하십시오.
SES에서 ES5 / Strict로 직접 변환해야합니다.
표준의 부록 C 는 엄격 모드와 일반 모드의 차이점을 설명합니다.
엄격한 모드 제한 및 예외
- 식별자 "구현물", "인터페이스", "let", "package", "private", "protected", "public", "static"및 "yield"는 엄격 모드 코드 내에서 FutureReservedWord 토큰으로 분류됩니다. (7.6.12 [?]).
- 엄격한 모드 코드를 처리 할 때 적합한 구현은 B.1.1에 설명 된대로 OctalIntegerLiteral을 포함하도록 NumericLiteral (7.8.3)의 구문을 확장 할 수 없습니다.
- 엄격한 모드 코드 (10.1.1 참조)를 처리 할 때 적합한 구현은 B.1.2에 설명 된대로 OctalEscapeSequence를 포함하도록 EscapeSequence의 구문을 확장 할 수 없습니다.
- 선언되지 않은 식별자 또는 다른 방법으로 해결할 수없는 참조에 할당해도 전역 개체에 속성이 만들어지지 않습니다. 엄격한 모드 코드 내에서 간단한 할당이 발생하면 LeftHandSide를 확인할 수없는 참조로 평가해서는 안됩니다. 이것이 발생하면 ReferenceError 예외가 발생합니다 (8.7.2). LeftHandSide는 속성 값이 {[[Writable]] : false} 인 데이터 속성, 속성 값이 {[[Set]] : undefined} 인 접근 자 속성 또는 존재하지 않는 데이터 속성에 대한 참조가 아닐 수도 있습니다. [[Extensible]] 내부 속성 값이 false 인 객체의 속성입니다. 이 경우 TypeError 예외가 발생합니다 (11.13.1).
- 식별자 평가 또는 인수는 할당 연산자 (11.13) 또는 PostfixExpression (11.3) 또는 Prefix Increment (11.4.4) 또는 Prefix Decrement (11.4.5) 연산자에 의해 운영되는 UnaryExpression의 LeftHandSideExpression으로 표시되지 않을 수 있습니다. . 엄격 모드 함수의 인수 객체는 액세스 할 때 TypeError 예외를 발생시키는 "caller"및 "callee"라는 구성 할 수없는 접근 자 속성을 정의합니다.
- 엄격 모드 함수의 인수 객체는 배열 인덱스 속성 값을 해당 함수의 해당 형식 매개 변수 바인딩과 동적으로 공유하지 않습니다. (10.6). 엄격 모드 함수의 경우, 인수 오브젝트가 작성되면 로컬 ID 인수를 인수 오브젝트에 바인딩하는 것은 변경 불가능하므로 지정 표현식의 대상이 아닐 수 있습니다. (10.5).
- It is a SyntaxError if strict mode code contains an ObjectLiteral with more than one definition of any data property (11.1.5). It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code or if its FunctionBody is strict code (11.1.5).
- Strict mode eval code cannot instantiate variables or functions in the variable environment of the caller to eval. Instead, a new variable environment is created and that environment is used for declaration binding instantiation for the eval code (10.4.2).
- If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object (10.4.3, 11.1.1, 15.3.4.3, 15.3.4.4).
- When a delete operator occurs within strict mode code, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name(11.4.1).
- When a delete operator occurs within strict mode code, a TypeError is thrown if the property to be deleted has the attribute { [[Configurable]]:false } (11.4.1). It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code and its Identifier is eval or arguments (12.2.1).
- Strict mode code may not include a WithStatement. The occurrence of a WithStatement in such a context is an SyntaxError (12.10).
- It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the Catch production is eval or arguments (12.14.1)
- It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)
- A strict mode function may not have two or more formal parameters that have the same name. An attempt to create such a function using a FunctionDeclaration, FunctionExpression, or Function constructor is a SyntaxError (13.1, 15.3.2).
- An implementation may not extend, beyond that defined in this specification, meanings within strict mode functions of properties named caller or arguments of function instances. ECMAScript code may not create or modify properties with these names on function objects that correspond to strict mode functions (10.6, 13.2, 15.3.4.5.3).
- It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name (13.1). Attempting to dynamically define such a strict mode function using the Function constructor (15.3.2) will throw a SyntaxError exception.
ECMAScript 5 introduced the concept of strict mode.
Invoking Strict Mode in Code
Strict mode applies to entire scripts or to individual function. It doesn’t apply to block statement enclosed in {} braces, attempting to apply it to such contexts does nothing.
Entire Script:
Let say we are creating app.js so adding first statement use script will enforce strict mode for entire code.
// app.js whole script in strict mode syntax
“use strict”;
// Now you can start writing your code
Strict mode for function:
To Invoke strict mode for a function, put the exact statement “use strict”; in the start of function body before any other statement.
function yourFunc(){
"use strict";
// Your function code logic
}
Strict mode incorporate several changes to normal Javascript semantics. First strict mode eliminate some JavaScript silent error by changing them to throw errors.
For Instance: Code using Strict Mode
In above code example without using strict mode in code It won't throw an error. As we are accessing variable x
without declaring it. So in strict mode accessing undeclared variable throw an error.
Now let's try to access variable x without declaring it without strict mode.
(function(){
x = 3;
})();
// Will not throw an error
Advantage of using strict mode:
- Eliminate JavaScript silent errors by throwing error.
- Fixes mistake that make it difficult for JavaScript engine to perform optimisation.
- Make code run faster sometime than identical code that’s not in strict mode
- Prohibits some syntax likely to be defined in future version of ECMAScript.
Strict mode makes several changes to normal JavaScript semantics.
strict mode eliminates some JavaScript silent errors by changing them to throw errors.
strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations.
strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
ECMAScript5
introduces some new objects and properties and also the so-called "strict mode"
.
Strict mode is a subset of the language that excludes deprecated features. The strict mode is opt-in and not required, meaning that if you want your code to run in the strict mode, you declare your intention using (once per function, or once for the whole program) the following string:
"use strict";
2017 and I finally found the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.
Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
Question:
Following is the problem I encountered, I was following a tutorial and it ended up trying to compile following scss
file and trying to generate CSS code from it,
.fatty{
width: percentage(6/7);
}
using following gulpfile.js
task:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
return gulp.src('app/scss/styles.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'))
});
So the error I'm getting is as follows:
~/htdocs/Learning/gulp1/node_modules/gulp-sass/index.js:66
let sassMap;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
// stacktrace here...
Solution:
So it shows me index.js
file which is inside my gulp-sass module (which is basically locked and shouldn't be edited). But if I go forcefully and add the "use_strict"
on the top of that index.js
file, it runs my task smoothly.
I was helpless, so I keep using this as the solution! But then after going through some other SO Q&A's I saw following answer as follows:
sudo npm install -g n
sudo n stable
and sooner I updated my NodeJs (to Version10.x), and then rebuilt Gulp by running following commands as Terminal instructed me:
npm rebuild node-sass --force
And it's all okay. So that's how it got resolved. I undone the changes I did for index.js
gulp module file. And now it runs smoothly.
Hope this answer will be helpful to someone out there!
참고URL : https://stackoverflow.com/questions/8651415/what-is-strict-mode-and-how-is-it-used
'Programing' 카테고리의 다른 글
위치와 함께 작동하지 않는 'transform3d': 고정 하위 (0) | 2020.07.01 |
---|---|
CSS 또는 HTML에 이미지를 data / base64로 포함시켜야합니까? (0) | 2020.07.01 |
링크 및 스크립트 태그에서 CSS 및 Javascript URL에“? v = 1”을 추가하면 어떤 기능이 있습니까? (0) | 2020.07.01 |
.NET에서 Getter 및 Setter 선언 (0) | 2020.07.01 |
커맨드 라인에서 클래스 경로에 항아리 포함 (javac 또는 apt) (0) | 2020.07.01 |