내 JavaScript 함수 이름이 충돌하는 이유는 무엇입니까?
변수와 함수가 할당 된 함수가 이름이 충돌 할 때 어떤 일이 발생하는지보기 위해 다음 스크립트를 작성했습니다.
var f = function() {
console.log("Me original.");
}
function f() {
console.log("Me duplicate.");
}
f();
내가 얻는 출력은 "Me original"입니다. 다른 함수가 호출되지 않은 이유는 무엇입니까?
또한 원래 할당을로 변경 var f = new function() {
하면 "Me original"이 표시되고 TypeError가 object is not a function
. 누군가 설명해 주시겠습니까?
함수 선언은 JavaScript에서 호이스트 (맨 위로 이동)됩니다. 구문 분석 순서는 올바르지 않지만 함수 선언이 호이스트되기 때문에 가지고있는 코드는 의미 상 다음과 동일합니다.
function f() {
console.log("Me duplicate.");
}
var f = function() {
console.log("Me original.");
}
f();
차례로 함수 이름을 제외하고는 다음과 같습니다.
var f = function() {
console.log("Me duplicate.");
}
var f = function() {
console.log("Me original.");
}
f();
차례로 가변 호이 스팅으로 인해 다음과 같습니다.
var f;
f = function() {
console.log("Me duplicate.");
}
f = function() {
console.log("Me original.");
}
f();
당신이 얻는 것을 설명하는 것은 함수를 재정의하고 있습니다. 보다 일반적으로 var
JavaScript 에서는 여러 선언이 허용되며 이는 var x = 3; var x = 5
완벽하게 합법적입니다. 새로운 ECMAScript 6 표준에서 let
명령문은이를 금지합니다.
@kangax 의이 기사 는 자바 스크립트의 기능을 이해하는 데 환상적인 작업을 수행합니다.
후속 질문에 아무도 답변하지 않은 것 같으면 여기서 답변하겠습니다. 일반적으로 후속 질문은 별도의 질문으로해야합니다.
이유를 물었습니다.
var f = new function() {
console.log("Me original.");
}
function f() {
console.log("Me duplicate.");
}
f();
"나의 원본"을 인쇄합니다. 그리고 오류.
여기서 일어나는 일은 new
함수가 생성자로 사용되는 원인입니다. 따라서 이것은 다음과 같습니다.
function myConstructor() {
console.log("Me original.");
}
var f = new myConstructor();
function f() {
console.log("Me duplicate.");
}
f();
And thanks to the function hoisting that Benjamin explained, the above is essentially equivalent to this:
var myConstructor = function() {
console.log("Me original.");
};
var f = function() {
console.log("Me duplicate.");
};
f = new myConstructor();
f();
This expression:
var f = new function() {
console.log("Me original.");
}
causes a new object to be constructed and assigned to f
, using an anonymous function as the constructor. "Me original." is printed out as the constructor executes. But the object that is constructed is not itself a function, so when this eventually executes:
f();
you get an error, because f
is not a function.
Forgive me if this is the wrong way to approach adding a point. I haven't been around here all the much, and would welcome constructive direction and/or criticism.
Benjamin's answer addresses the OP's question excellently, but I'd like to add one tweak that'll give us a full tour of hoisting and its oddities.
If we begin the original code with a call to f
, like so:
f();
var f = function() {
console.log("Me original.");
};
function f() {
console.log("Me duplicate.");
}
f();
The output will then be:
Me duplicate.
Me original.
The reason being that var
and function
statements are hoisted in slightly different ways.
For var
the declaration is moved to the top of the current scope*, but any assignment is not hoisted. As far as the value of the declared var goes, it's undefined until the original assignment line is reached.
For function
statements, both the declaration and definition are hoisted. Function expressions, as used in the var f = function() {...
construct, are not hoisted.
So after hoisting, execution is as if the code were:
var f; // declares var f, but does not assign it.
// name and define function f, shadowing the variable
function f() {
console.log("Me duplicate.");
}
// call the currently defined function f
f();
// assigns the result of a function expression to the var f,
// which shadows the hoisted function definition once past this point lexically
f = function() {
console.log("Me original.");
}
// calls the function referenced by the var f
f();
*All JavaScript scope is lexical, or function, scope, but it seemed like it would just confuse things to use the f word at that point.
참고URL : https://stackoverflow.com/questions/23889317/why-are-my-javascript-function-names-clashing
'Programing' 카테고리의 다른 글
객체 속성이 ko.observable인지 확인합니다. (0) | 2020.08.23 |
---|---|
Jade 대신 Express에서 HTML 사용 (0) | 2020.08.23 |
HtmlWebpackPlugin은 루트가 아닌 웹 사이트 경로를로드 할 때 중단되는 상대 경로 파일을 삽입합니다. (0) | 2020.08.23 |
ESRI : 소스 맵을 구문 분석하지 못했습니다. (0) | 2020.08.23 |
C ++ 경고 : double을 0으로 나누기 (0) | 2020.08.23 |