program tip

작동하지 않는 JavaScript 규칙은 무엇입니까?

radiobox 2020. 8. 15. 09:03
반응형

작동하지 않는 JavaScript 규칙은 무엇입니까?


작동하지 않는 JavaScript 규칙은 무엇입니까? Python pass명령과 같습니다.

  • 한 가지 옵션은 단순히 빈 함수입니다. function() {}
  • jQuery는 $.noop()단순히 위의 빈 함수를 호출하는을 제공합니다 .
  • 단순히 false또는 값을 입력해도 0됩니까?

맥락에서 ...이 모든 것이 Chrome에서 오류를 발생시키지 않고 작동합니다.

var a = 2;
(a === 1) ? alert(1) : function() {};
(a === 1) ? alert(1) : $.noop();
(a === 1) ? alert(1) : false;
(a === 1) ? alert(1) : 0;

편집 : 많은 사람들이 "이러지 마세요! 코드 구조를 변경하세요!"라고 대답했습니다. 이것은 누군가가 브라우저를 스니핑하는 방법을 묻는 게시물을 생각 나게합니다. 그는 "그렇게 하지마! 그것은 악하다"라는 글을 많이 받았지만 아무도 그에게 브라우저 냄새를 맡는 방법을 알려주지 않았다 . 이것은 코드 리뷰가 아닙니다. 변경할 수없는 레거시 코드를 처리하고 있으며 일부 함수가 전달되지 않으면 오류가 발생한다고 상상해보십시오. 또는 간단히 말해서 고객이 원하는 방식이고 고객 이 비용을 지불하고 있습니다. 따라서 정중하게 대답 해주십시오 . JavaScript에서 "no operation"기능을 지정하는 가장 좋은 방법은 무엇입니까?

EDIT2 : 이들 중 하나는 어떻습니까?

true;
false;
0;
1;
null;

원래의 질문에 답하기 위해 순수 자바 스크립트에서 noop 함수를 가장 우아하고 깔끔하게 구현 한 것은 ( 여기 에서도 논의 된 바와 같이 ) Function.prototype 입니다. 아래 스 니펫은 사용법을 보여줍니다.

setTimeout(Function.prototype, 10000);

세 가지 브라우저 (Chrome, Firefox 및 IE 11) 모두 위의 실행시 10 초 후에 인터프리터가 다시 표시되지 않습니다 (디버거에서 "단계별 실행"모드를 사용하여 단계별로 테스트 할 수 있음).

대부분의 브라우저가 이러한 방식으로 정의 된 noop를 실행하기 위해 아무것도하지 않는 것 같기 때문에 이것이 "진정한 noop"이지만 (따라서 CPU주기를 절약합니다) 이와 관련된 성능 문제가있을 수 있습니다 (다른 사람이 의견이나 다른 답변).

그러나 자신의 noop 함수를 쉽게 정의 할 수 있으며 실제로 많은 라이브러리와 프레임 워크도 noop 함수를 제공합니다. 다음은 몇 가지 예입니다.

var noop = function () {};           // Define your own noop in ES3 or ES5
const noop = () => {};               // OR Define your own noop in ES6
setTimeout(noop, 10000);             // Using the predefined noop

setTimeout(function () {} , 10000);  // Using directly in ES3 or ES5
setTimeout(() => {} , 10000);        // Using directly in ES6 as Lambda (arrow function)

setTimeout(angular.noop, 10000);     // Using with angular 1.x
setTimeout(jQuery.noop, 10000);      // Using with jQuery

다음은 noop 함수 (또는 관련 토론 또는 Google 검색)의 다양한 구현의 알파벳순 목록입니다.

Angular 1.x , Angular 2+ (기본 구현이없는 것 같음-위에 표시된대로 직접 사용), Ember , jQuery , Lodash , NodeJS , Ramda , React (기본 구현이없는 것 같음 -직접 사용 위와 같이), RxJS , 밑줄

BOTTOM LINE : Function.prototype은 Javascript에서 noop를 표현하는 우아한 방법이지만 사용과 관련된 성능 문제가있을 수 있습니다. 따라서 위에 표시된대로 직접 정의하고 사용하거나 코드에서 사용할 수있는 라이브러리 / 프레임 워크에서 정의한 것을 사용할 수 있습니다.


가장 간결하고 성능이 좋은 무 조작은입니다 빈 화살표 기능 : ()=>{}.

화살표 함수 는 IE를 제외한 모든 브라우저에서 기본적으로 작동합니다 ( 필요한 경우 바벨 변환 이 있음).MDN


()=>{}Function.Prototype

  • ()=>{}이다 87 % 더 빠른 것보다 Function.prototype크롬 육십칠인치
  • ()=>{}이다 25 % 더 빠른 것보다 Function.prototype파이어 폭스 육십인치
  • ()=>{}이다 85 % 더 빠른 것보다 Function.prototype가장자리에서 (2018년 6월 15일) .
  • ()=>{} is 65% less code than Function.prototype.

The test below heats up using the arrow function to give bias to Function.prototype, yet the arrow function is the clear winner:

const noop = ()=>{};
const noopProto = Function.prototype;

function test (_noop, iterations) {
    const before = performance.now();
    for(let i = 0; i < iterations; i++) _noop();
    const after = performance.now();
    const elapsed = after - before;
    console.info(`${elapsed.toFixed(4)}MS\t${_noop.toString().replace('\n', '')}\tISNOOP? ${_noop() === undefined}`);
    return elapsed;
}

const iterations = 10000000
console.info(`noop time for ${iterations.toLocaleString()} iterations`)
const timings = {
    noop: test(noop, iterations),
    noopProto: test(noopProto, iterations)
}

const percentFaster = ((timings.noopProto - timings.noop)/timings.noopProto).toLocaleString("en-us", { style: "percent" });
console.info(`()=>{} is ${percentFaster} faster than Function.prototype in the current browser!`)


whatever you tend to achieve here is wrong. Ternary expressions shall not be used as a full statement, only in expression, so the answer to your question is:

none of your suggestions, instead do:

var a = 2;
if (a === 1)
    alert(1)
// else do nothing!

then the code is easily understandable, readable and as much efficient as it can get.

Why make it more difficult, when it can be simple?

edit:

So then, does a "no-operation" command basically indicate an inferior code structure?

You're missing my point. All the above is about the ternary expression x ? y : z.

But, a no operation command does not makes sense in higher level languages such as Javascript.

It is usually used, in lower level languages such as assembly or C, as a way to make the processor do nothing for one instruction for timing purposes.

In JS, whether you do 0;, null;, function () {}; or an empty statement, there are great chances that it will be ignored by the interpretor when it is reading it, but before it gets interpreted, so in the end, you'll just make your program be loaded more slowly by a really tiny amount of time. Nota Bene: I'm assuming this, as I'm not involved in any widely used JS interpreter, and there are chances each interpreter has its own strategy.

In case you use something a bit more complicated, like $.noop() or var foo = function () {}; foo(), then the interpreter may do an unuseful function call that will end up spoiling a few bytes of your function stack, and a few cycles.

The only reason I see a function such as $.noop() would exist, would be to be able to still give a callback function to some event function that would throw an exception if it can't call that callback. But then, it's necessarily a function you need to give, and giving it the noop name is a good idea so you're telling your readers (and that may be you in 6 months) that you purposely give an empty function.

In the end, there's no such thing as "inferior" or "superior" code structure. You're either right or wrong in the way you use your tools.. Using a ternary for your example is like using a hammer when you want to screw. It'll work, but you're not sure you can hang something on that screw.

What could be considered either "inferior" or "superior" is the algorithm and ideas you put in your code. But that's another thing.


I think jQuery noop() is mostly intended to prevent code from crashing by providing a default function when the requested one is not available. For example, considering the following code sample, $.noop is chosen if fakeFunction is not defined, preventing the next call to fn from crashing :

var fn = fakeFunction || $.noop;
fn() // no crash

Then, noop() allows to save memory by avoiding to write the same empty function multiple times everywhere in your code. By the way, $.noop is a bit shorter than function(){} (6 bytes saved per token). So, there is no relationship between your code and the empty function pattern. Use null, false or 0 if you like, in your case there will be no side effect. Furthermore, it's worth noting that this code...

true/false ? alert('boo') : function(){};

... is completely useless since you'll never call the function, and this one...

true/false ? alert('boo') : $.noop();

... is even more useless since you call an empty function, which is exactly the same as...

true/false ? alert('boo') : undefined;

Let's replace the ternary expression with an if statement to see how much it's useless :

if (true/false) {
    alert('boo');
} else {
    $.noop(); // returns undefined which goes nowhere
}

You could simply write :

if (true/false) alert('boo');

Or even shorter :

true/false && alert('boo');

To finally answer your question, I guess a "conventional no operation" is the one which is never written.


I use:

 (0); // nop

To test execution time of this run as:

console.time("mark");
(0); // nop
console.timeEnd("mark");

result: mark: 0.000ms

Using Boolean( 10 > 9) can be reduced it to simply ( 10 > 9) which returns true. Coming up with the idea to use a single operand I fully expected (0); would return false, but it simply returns the argument back as can be reviewed by performing this test at the console.

> var a = (0);
< undefined
> a
< 0

참고URL : https://stackoverflow.com/questions/21634886/what-is-the-javascript-convention-for-no-operation

반응형