Program Club

특정 기능에 대해 ECMAscript 엄격 모드를 비활성화 할 수 있습니까?

proclub 2020. 11. 8. 11:29
반응형

특정 기능에 대해 ECMAscript 엄격 모드를 비활성화 할 수 있습니까?


MDC 또는 ECMAscript 사양에 대한 내 질문에 대해 아무것도 찾지 못했습니다. 아마도 누군가는 이것을 해결하는 더 '해키'방법을 알고있을 것입니다.

"use strict"내 환경의 모든 자바 스크립트 파일을 호출 하고 있습니다. 내 모든 파일은 이렇게 시작합니다.

(function(win, doc, undef) {
    "use strict";

    // code & functions
}(window, window.document));

이제 오류를 처리하는 사용자 지정 함수가 있습니다. 이 함수는 .caller속성을 사용하여 컨텍스트 스택 추적 을 제공합니다 . 다음과 같이 보입니다.

var chain = (function() {
    var _parent = _error,
        _ret = '';

    while( _parent.caller ) {
        _ret += ' -> ' + _parent.caller.name;
        _parent = _parent.caller;
    }

    return _ret;
}());

그러나 물론 Strict 모드 .caller에서는 회수 할 때 던지는 삭제 불가능한 소품입니다. 그래서 제 질문은 "기능면에서 더 엄격한" 비활성화 하는 방법을 아는 사람이 있습니까?

"use strict";호출 된 후 모든 함수에 상속됩니다. 이제 우리는 특정 함수 "use strict";의 맨 위를 호출하여 엄격 모드를 사용할 가능성이 있지만 그 반대를 달성하는 방법이 있습니까?


아니요, 기능별로 엄격 모드를 비활성화 할 수 없습니다.

엄격 모드는 어휘 적으로 작동한다는 것을 이해하는 것이 중요합니다 . 의미 — 실행이 아니라 함수 선언에 영향을줍니다. 엄격한 코드 내에서 선언 된 모든 함수 자체적으로 엄격한 함수가됩니다. 그러나 엄격한 코드 내에서 호출 되는 함수 가 반드시 엄격한 것은 아닙니다.

(function(sloppy) {
  "use strict";

   function strict() {
     // this function is strict, as it is _declared_ within strict code
   }

   strict();
   sloppy();

})(sloppy);

function sloppy(){
  // this function is not strict as it is _declared outside_ of strict code
}

엄격한 코드 외부에서 함수를 정의한 다음 이를 엄격한 함수 로 전달 하는 방법에 주목하십시오 .

예제에서 비슷한 작업을 수행 할 수 있습니다. "조잡한"함수를 가진 객체를 가지고 그 객체를 즉시 호출되는 엄격한 함수에 전달합니다. 물론 "조잡한"함수가 주 래퍼 함수 내에서 변수를 참조해야하는 경우에는 작동하지 않습니다.

또한 다른 사람이 제안한 간접 평가 는 여기에서 실제로 도움이되지 않습니다. 그것이하는 일은 글로벌 컨텍스트에서 코드를 실행하는 것입니다. 로컬로 정의 된 함수를 호출하려고하면 간접 평가에서도 찾을 수 없습니다.

(function(){
  "use strict";

  function whichDoesSomethingNaughty(){ /* ... */ }

  // ReferenceError as function is not globally accessible
  // and indirect eval obviously tries to "find" it in global scope
  (1,eval)('whichDoesSomethingNaughty')();

})();

전역 평가에 대한 이러한 혼란은 아마도 전역 평가를 사용하여 엄격 모드 ( this더 이상 단순히 액세스 할 수 없음) 내에서 전역 개체에 액세스 할 수 있다는 사실에서 비롯된 것입니다 .

(function(){
  "use strict";

  this; // undefined
  (1,eval)('this'); // global object
})();

하지만 질문으로 돌아가서 ...

You can kind of cheat and declare a new function via Function constructor — which happens to not inherit strictness, but that would rely on (non-standard) function decompilation and you would lose ability to reference outer variables.

(function(){
  "use strict";

  function strict(){ /* ... */ }

  // compile new function from the string representation of another one
  var sneaky = Function('return (' + strict + ')()');

  sneaky();
})();

Note that FF4+ seems to disagree with spec (from what I can tell) and incorrectly marks function created via Function as strict. This doesn't happen in other strict-mode-supporting implementations (like Chrome 12+, IE10, WebKit).


(From http://javascriptweblog.wordpress.com/2011/05/03/javascript-strict-mode/)

(...) Strict Mode is not enforced on non-strict functions that are invoked inside the body of a strict function (either because they were passed as arguments or invoked using call or apply).

So if you setup the error methods in a different file, without strict mode, and then pass them as a parameter, like this:

var test = function(fn) {
  'use strict';
  fn();
}

var deleteNonConfigurable = function () {
  var obj = {};
  Object.defineProperty(obj, "name", {
    configurable: false
  });
  delete obj.name; //will throw TypeError in Strict Mode
}

test(deleteNonConfigurable); //no error (Strict Mode not enforced)

...it should work.


An alternative is simply doing this

var stack;
if (console && console.trace) {
     stack = console.trace();
} else {
    try {
        var fail = 1 / 0;
    } catch (e) {
        if (e.stack) {
            stack = e.stack;
        } else if (e.stacktrace) {
            stack = e.stacktrace;
        }
    }
}
// have fun implementing normalize.
return normalize(stack);

참고URL : https://stackoverflow.com/questions/6020178/can-i-disable-ecmascript-strict-mode-for-specific-functions

반응형