programing

JavaScript에서 void 연산자의 요점은 무엇입니까?

minecode 2021. 1. 15. 07:57
반응형

JavaScript에서 void 연산자의 요점은 무엇입니까?


void코드에서 연산자를 사용하는 사람들을 보았습니다 . 나는 또한이를 보았다 href속성 : javascript:void(0)보다 나은 보이지 않는javascript:;

그렇다면 void연산자 사용의 정당성은 무엇 입니까?


JavaScript void 연산자는 명시 적으로 undefined를 반환하는 데 사용됩니다. 단항 연산자로, 하나의 피연산자 만 사용할 수 있습니다. 아래에 표시된 것처럼 독립형 또는 괄호와 함께 사용할 수 있습니다.

void expression;
void(expression);

몇 가지 예를 보자

void 0; //returns undefined
void(1); //returns undefined

void 'hello'; //undefined
void {}; //undefined
void []; //undefined

void myFunction(); 
void(myFunction());

왜 undefined를 반환하는 대신 undefined를 반환하기 위해 특수 키워드가 필요한지 묻는 경우. 글쎄, 그 이유는 ES5 이전에는 실제로 var undefined = "hello"또는 var undefined = 23과 같이 원래 undefined에 새 값을 할당 할 수 있으며 대부분의 브라우저에서 지원할 수 있기 때문입니다. 그래서 원래 undefined를 반환하고 void 연산자가 사용되었는지 두 배로 확인하십시오. 하지만 그다지 인기있는 연산자는 아니며 거의 사용되지 않습니다.

void가있는 함수의 예를 보겠습니다.

//just a normal function
function test() {
  console.log('hello');
  return 2;
}

//lets call it
test(); //output is hello followed by 2

//now lets try with void
void test(); //output is hello followed by undefined

void는 함수에서 반환을 취소하고 undefined를 명시 적으로 반환합니다.

내 튜토리얼 게시물에서 더 많은 것을 읽을 수 있습니다 : https://josephkhan.me/the-javascript-void-operator/


링크에서의 사용 설명 :

이것이 북마크릿이 종종 void () 내부에 코드를 래핑하거나 브라우저가 북마크릿 실행 결과를 표시하는 것을 막기 위해 아무것도 반환하지 않는 익명 함수를 감싸는 이유입니다. 예를 들면 :

javascript:void(window.open("dom_spy.html"))

무언가를 반환하는 코드 (이 경우 새 창 인스턴스)를 직접 사용하면 브라우저에 다음이 표시됩니다.

javascript:window.open("dom_spy.html");

Firefox에서는 위의 내용이 표시됩니다.

[object Window]

undefined값은 ES1.3까지 자바 스크립트에서 직접 액세스 할 수 없었다.

void <expression>따라서이 값에 대한 액세스를 허용하기 위해 연산자 가 포함되었습니다.

특히 Web API (예 : 이벤트 핸들러)로 작업 할 때 표현식의 결과가 일관되게 유지되도록하는 것이 유용합니다 undefined.

undefinedES1.3의 전역 개체에 속성이 추가 되었을 때의 유틸리티 void가 명확하지 않게되었습니다.

따라서 귀하의 질문.


다음을 고려하세요:

<a href="javascript:void(fish=document.getElementById('foo').value);void(document.getElementById('bar').value=fish);">With Void</a>

<a href="javascript:fish=document.getElementById('foo').value;document.getElementById('bar').value=fish;">Without Void</a>

<input type="text" id="foo" value="one fish" />
<input type="text" id="bar" value="no fish" />

첫 번째 링크는 텍스트 필드의 값을 바꿉니다. 두 번째 링크는 "one fish"라는 텍스트가있는 새 페이지를 엽니 다. 를 사용하는 경우 javascript: link표현식이 null또는 이외의 것을 반환하는 분 undefined에 브라우저는이를 링크가 수행해야하는 작업으로 해석합니다. 모든 표현식 / 문을 void()함수 로 래핑 하면 전체 코드 스 니펫이 실행됩니다. 요즘은 onclick속성 을 사용 하거나 별도의 자바 스크립트 블록 / 파일에 이벤트 핸들러를 설정하는 것이 "표준"이기 때문에 북마크릿 에서 주로 사용됩니다 .

As for javascript: vs. javascript:void(), the first statement is ambiguous. You're saying, "hey, I want to run some javascript", but then you don't provide any code. It's not necessarily clear what the browser should do here. With the second statement you're saying "hey, run some javascript", and your code eventually returns undefined, which the browser knows means "do nothing".

Since I'm here, I'll also point out that using either javascript: or javascript:void(); has fallen out of favor with most people who care about markup. The better thing to do is have your onclick handler return false, and have the link pointed towards a page/resource that makes sense for people who have javascript turned off, or are using a javascript blocker such as NoScript.

ReferenceURL : https://stackoverflow.com/questions/666936/what-is-the-point-of-void-operator-in-javascript

반응형