ES6 즉시 화살표 기능을 호출
왜 Node.js
콘솔 (4.1.1 및 5.3.0에서 테스트)에서 작동하지만 브라우저 (Chrome에서 테스트)에서 작동하지 않습니까? 이 코드 블록은 기록하는 익명 함수를 작성하고 호출해야합니다 Ok
.
() => {
console.log('Ok');
}()
또한 위의 노드에서 작동 하지만 작동 하지 않습니다.
n => {
console.log('Ok');
}()
이것도 아닙니다 :
(n) => {
console.log('Ok');
}()
이상한 점은 매개 변수가 추가되면 실제로 SyntaxError
호출하는 부분에 실제로 a 를 던진다는 것 입니다.
이름을 필요로하지 않고 유효한 JavaScript로 만드는 함수 정의 대신 함수 표현식 으로 만들어야합니다 .
(() => {
console.log('Ok');
})()
IIFE 와 동일
(function(){
console.log('Ok')
})();
그리고 이것이 Node.js에서 작동하지만 크롬에서는 작동하지 않는 가능한 이유는 파서가이를 자체 실행 함수로 해석하기 때문입니다.
function() { console.log('hello'); }();
Node.js
이것은 잘 작동합니다. 이것은 함수 표현식이며 크롬과 파이어 폭스이며 대부분의 브라우저는이 방식으로 해석합니다. 수동으로 호출해야합니다.
파서가 함수 표현식을 기대하도록 지시하는 가장 널리 사용되는 방법은 JavaScript에서 parens에 명령문을 포함 할 수 없기 때문에 함수 표현식을 parens로 감싸는 것입니다. 이때 파서가 함수 키워드를 만나면 함수 선언이 아니라 함수 표현식으로 구문 분석하는 것을 알게됩니다.
매개 변수가 지정된 버전 과 관련하여 작동합니다.
((n) => {
console.log('Ok');
})()
이들 중 어느 것도 괄호없이 작동해서는 안됩니다.
왜?
사양에 따르면 :
- ArrowFunction 은 AssignmentExpression 아래 에 나열됩니다.
- (A)의 LHS CallExpression는 해야 MemberExpression , SuperCall 또는 CallExpression
그래서 ArrowFunction은 a의 LHS에있을 수 없습니다 CallExpression .
이것이 효과적으로하는 방법을 의미 =>
, 해석되어야하는 것은 대입 연산자와 같은 수준의 동일한 종류에 작동하다 =
, +=
등
의미
x => {foo}()
하지 않습니다 될(x => {foo})()
- 통역사는 다음과 같이 해석하려고 시도합니다.
x => ({foo}())
- 따라서 여전히 SyntaxError입니다.
- 따라서 인터프리터는
(
필수 항목이 잘못되었다고 판단하고 SyntaxError 를 발생시킵니다.
여기 Babel에도 버그가있었습니다 .
이와 같은 문제가 발생하는 이유는 콘솔 자체가 현재 대상으로하는 컨텍스트의 전체 범위를 모방하려고하기 때문입니다. 또한 콘솔에 작성한 명령문 및 표현식에서 리턴 값을 캡처하여 결과로 표시되도록 시도합니다. 예를 들어,
> 3 + 2
< 5
여기서는 표현식 인 것처럼 실행되지만 명령문 인 것처럼 작성했습니다. 일반 스크립트에서는 값이 삭제되지만 여기서는 전체 명령문을 함수 컨텍스트 및 명령문으로 랩핑하는 것과 같이 코드가 내부적으로 엉망이 return
되어 발생하는 문제를 포함하여 모든 종류의 이상한 효과가 발생합니다.
This is also one of the reasons why some bare ES6 code in scripts works fine but doesn't in Chrome Dev Tools console.
Try executing this in Node and Chrome console:
{ let a = 3 }
In Node or a <script>
tag it works just fine, but in the console, it gives Uncaught SyntaxError: Unexpected identifier
. It also gives you a link to the source in the form of VMxxx:1
which you can click to inspect the evaluated source, which shows up as:
({ let a = 3 })
So why did it do this?
The answer is that it needs to convert your code into an expression so that the result can be returned to the caller and displayed in the console. You can do this by wrapping the statement in parentheses, which makes it an expression, but it also makes the block above syntactically incorrect (an expression cannot have a block declaration).
The console does try to fix these edge cases by being smart about the code, but that's beyond the scope of this answer, I think. You can file a bug to see if that's something they'd consider fixing.
Here's a good example of something very similar:
https://stackoverflow.com/a/28431346/46588
The safest way to make your code work is to make sure it can be run as an expression and inspect the SyntaxError
source link to see what the actual execution code is and reverse engineer a solution from that. Usually it means a pair of strategically placed parentheses.
In short: the console tries to emulate the global execution context as accurately as possible, but due to the limitations of interaction with the v8 engine and JavaScript semantics this is sometimes hard or impossible to solve.
참고URL : https://stackoverflow.com/questions/34589488/es6-immediately-invoked-arrow-function
'IT' 카테고리의 다른 글
터치 장치의 버튼에 끈적임 호버 효과를 방지하는 방법 (0) | 2020.07.04 |
---|---|
Bootstrap은 왜 line-height 속성을 1.428571429로 설정합니까? (0) | 2020.07.04 |
React.js : innerHTML 대 위험한 설정 (0) | 2020.07.04 |
버블 정렬 숙제 (0) | 2020.07.04 |
typeError : console.log.apply에서 잘못된 호출 (0) | 2020.07.04 |