code

정의되지 않은 것을 덮어 쓰지 않는다고 가정하는 것이 JavaScript에서 실제로 얼마나 위험한가요?

codestyles 2020. 9. 22. 08:14
반응형

정의되지 않은 것을 덮어 쓰지 않는다고 가정하는 것이 JavaScript에서 실제로 얼마나 위험한가요?


때마다 사람에 대해 테스트를 언급 undefined, 그것의 뾰족한 밖으로undefined 있도록 키워드 아닌 이 설정 될 수"hello" 있도록, 당신이 사용해야하는 typeof x == "undefined" 대신. 이것은 나에게 우스꽝스러워 보인다. 아무도 그렇게하지 않을 것이고, 그렇게한다면 그들이 작성한 코드를 절대 사용하지 않을 충분한 이유가 될 것입니다.

내가 발견 한 예를 실수로 설정 사람의 undefined에를 null,이는 그 가정 피하기위한 이유로 주어진 undefined덮어 쓰지 않습니다. 그러나 그들이 그렇게했다면 버그는 발견되지 않았을 것이고 나는 그것이 얼마나 더 나은지 보지 못합니다.

C ++에서 모든 사람은라고 말하는 것이 합법적이라는 것을 잘 알고 #define true false있지만 아무도 피하고 대신 true사용 하도록 조언 0 == 0하지 않습니다. 당신은 그 누구도 그렇게 할만큼 큰 멍청이가되지 않을 것이라고 가정하고 그들이 그렇게한다면 그들의 코드를 다시는 신뢰하지 마십시오.

다른 사람이 undefined(의도적으로) 할당 된 누군가를 실제로 물려서 코드를 깨뜨린 적이 있습니까? 아니면 가상의 위협에 가깝습니까? 나는 내 코드를 조금 더 읽기 쉽게 만들 수있는 기회를 갖고 싶다. 정말 나쁜 생각인가요?

다시 말해서, 정의되지 않은 재 할당으로부터 보호하는 방법을 묻는 것이 아닙니다 . 나는 그 트릭이 이미 100 번 쓰여진 것을 보았다. 그 속임수를 사용하지 않는 것이 얼마나 위험한지 묻고 있습니다.


아뇨. 이는 주로 ECMAScript 5와 호환되는 최신 브라우저에서 개발하기 때문입니다. ES5 표준 undefined은 현재 읽기 전용 임을 나타냅니다 . 엄격 모드를 사용하는 경우 (필요한 경우) 실수로 수정하려고하면 오류가 발생합니다.

undefined = 5;
alert(undefined); // still undefined
'use strict';
undefined = 5; // throws TypeError

하지 말아야 일은 자신의 범위가 있고 변경 가능한 것을 만드는 것입니다 undefined.

(function (undefined) {
    // don't do this, because now `undefined` can be changed
    undefined = 5;
})();

상수는 괜찮습니다. 여전히 불필요하지만 괜찮습니다.

(function () {
    const undefined = void 0;
})();

적절한 코드는 그런 일을 할 수 없습니다. 하지만 똑똑한 개발자 나 사용중인 플러그인 / 라이브러리 / 스크립트가 무엇을했는지 결코 알 수 없습니다. 반면에 최신 브라우저는 덮어 쓰기 undefined를 전혀 허용하지 않으므로 개발을 위해 이러한 브라우저를 사용하는 경우 코드가 덮어 쓰려고 시도하는 경우 신속하게 알 수 있습니다.


그리고 비록 당신이 그것을 요청하지 않았음에도 불구하고-많은 사람들은 아마도 더 일반적인 "재정의 된 보호 방법 undefined"문제를 찾을 때이 질문을 발견 할 것입니다 . 그래서 어쨌든 대답하겠습니다 :

브라우저의 수명에 undefined 관계없이 진정으로 정의되지 않은 상태 로 만드는 아주 좋은 방법 이 있습니다.

(function(undefined) {
    // your code where undefined is undefined
})();

이것은 지정되지 않은 인수가 항상이므로 작동합니다 undefined. 예를 들어 jQuery를 사용할 때 이와 같이 실제 인수를 받아들이는 함수를 사용하여 수행 할 수도 있습니다. 일반적으로 다음과 같은 방식으로 정상적인 환경을 유지하는 것이 좋습니다.

(function($, window, undefined) {
    // your code where undefined is undefined
})(jQuery, this);

그런 다음 해당 익명 함수 내부에서 다음 사항이 참인지 확인할 수 있습니다.

  • $ === jQuery
  • window === [the global object]
  • undefined === [undefined].

However, note that sometimes typeof x === 'undefined' is actually necessary: If the variable x has never been set to a value (contrary to being set to undefined), reading x in a different way such as if(x === undefined) will throw an error. This does not apply to object properties though, so if you know that y is always an object, if(y.x === undefined) is perfectly safe.


There's a simple solution to that: compare against void 0 which is always undefined.

Note that you should avoid == as it may coerce the values. Use === (and !==) instead.

That said, the undefined variable may be set by error if someone writes = instead of == when comparing something against undefined.


Only you know what code you use, and therefore how dangerous it is. This question can't be answered in the way you've clarified you want it answered.

1) Create a team policy, disallow redefining undefined, reserving it for its more popular usage. Scan your existing code for undefined left assignment.

2) If you don't control all the scenarios, if your code is used outside situations you or your policies control, then obviously your answer is different. Scan the code that does use your scripts. Heck, scan web for statistics of undefined left assignment if you wish, but I doubt that's been done for you, because it's easier to just pursue answer #1 or #3 here instead.

3) And if that answer isn't good enough, it's probably because, again, you require a different answer. Maybe you are writing a popular library that will be used inside corporate firewalls, and you don't have access to the calling code. Then use one of the other fine answers here. Note the popular jQuery library practices sound encapsulation, and begins:

(function( window, undefined ) {

Only you can answer your question in the specific way you seek. What more is there to say?

edit: p.s. if you really want my opinion, I'll tell you it's not dangerous at all. Anything that would be so likely to cause defects (such as assigning to undefined, which is obviously a well-documented risky behaviour) is itself a defect. It's the defect that is the risk. But that's just in my scenarios, where I can afford to hold that perspective. As I'd recommend you do, I answered the question for my use-cases.


It's safe to test against undefined. As you already mention. If you get to some code that overrides it (which is highly improvable), just don't use it anymore.

Maybe if you are creating a library for public use, you can use some of the techniques to avoid the user change it. But even in this case, it's their problem, not your library.


You can use undefined in your code when coding for browsers supporting ECMAScript 5.1 as it is immutable according to the language specification.

Also see this compatibility table or this caniuse ECMAScript 5 to see that all modern browsers (IE 9+) have implemented immutable undefined.


It's not dangerous at all. It can only be overwritten when running on an ES3 engine and that's not likely to be used any more.


First of all, if your code breaks it's probably not because some other developer out there "is trying to be a jerk" as you put it.

It's true that undefined is not a keyword. But it is a global level primitive. It was intended to be used like this (see "undefined" at developer.mozilla.org):

var x;
if (x === undefined) {
    // these statements execute
}
else {
    // these statements do not execute
}

The common alternative to that (also from MDN) and in my opinion the better way is:

// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
    // these statements execute
}

if(x === undefined){ // throws a ReferenceError

}

Which has a couple of advantages, the obvious one (from the comments) is that it does not trigger an exception when x is not declared. It's also worth noting that MDN also points out that it is important to use === over == in the first case because:

var x=null;
if (x === undefined) {
    // this is probably what you meant to do
    // these lines will not execute in this case
}
else if (x == undefined) {
    // these statements will execute even though x *is* defined (as null)
}
else {
    // these statements do not execute
}

This is another often overlooked reason why it is probably better to just use the second alternative in all cases.

Conclusion: It's not wrong to code it the first way, and certainly not dangerous. The argument you've seen that you use as an example against it (that it can be overwritten) is not the strongest argument for coding the alternative with typeof. But using typeof is stronger for one reason specifically: it doesn't throw an exception when your var is not declared. It could also be argued that using == instead of === is a common mistake in which case it's not doing what you expected it to. So why not use typeof?

참고URL : https://stackoverflow.com/questions/8783510/how-dangerous-is-it-in-javascript-really-to-assume-undefined-is-not-overwritte

반응형