문제

글로벌 객체 님의 핸들을 얻는 것이 좋습니다. > 알 수없는 호스트 환경에서 ?

ECMAScript는 내가 알고있는 전역 객체를 참조하는 내장 된 방법을 제공하지 않습니다. 그렇다면, 이것은 내가 찾고있는 대답입니다.

알려진 환경에서 에서, 전역 대상은 일반적으로 자체 참조 속성을 가지고 있습니다. 글로벌 객체는 VO 전역 객체의 속성은 전역 변수입니다. 그래서 우리는 어디에서나 전역 개체에 대한 핸들을 얻을 수 있습니다.

  • 웹 브라우저에서는 window 또는 self를 사용할 수 있습니다.

  • node.js에서는 global를 사용할 수 있습니다.

    그러나 이것은 반드시 모든 호스트 환경에서의 경우 일 필요는 없습니다. 내가 아는 한 Windows 스크립트 호스트는 전역 개체에 액세스 할 수있는 방법을 제공하지 않습니다. WSH에서 전역 개체를 가져 오는 권장되는 방법은 객체에 해결되지 않는 컨텍스트에서 this 키워드를 사용하는 것으로 보입니다. 예 :

    var GLOBAL = (function(){return this}());
    
    .

    이 기술은 호스트 환경에서 작동하지만 undefined this 엄격한 전역 개체를 참조하지 않기 때문에 엄격한 모드에서는 작동하지 않습니다. 모드 :

    엄격한 모드 코드 내 에서이 값을 평가하면이 값은 객체에 강제로 설정되지 않습니다. 이 값은 전역 오브젝트 로 변환되지 않으며 원시 값은 래퍼 객체로 변환되지 않습니다. 함수 호출 (function.prototype.apply 및 function.prototype.call을 사용하여 만든 호출 포함)을 통해 전달 된이 값은이 값을 객체 (10.4.3, 11.1.1, 15.3.4.3, 15.3)로 고정시키지 않습니다. 4.4).

    예상대로 다음 코드가 undefined를 만듭니다.

    (function(){
        "use strict";
        var GLOBAL = (function(){return this}());
        console.log(GLOBAL);
    }());
    
    .


    의 적절한 방법은 엄격한 모드 에 관계없이 모든 환경에서 전역 대상에 대한 핸들을 얻는 것입니까?

    그런데 내 현재 접근 방식은 다음과 같이 전역 객체를 참조하는 전역 변수를 위해

    var self, window, global = global || window || self;
    
    .

    ... 그런 다음 global를 사용하십시오. 나는 이것이 여러 가지 이유로 나쁜 해결책이라고 생각합니다. 대부분은 상당히 명백하고 WSH 문제를 해결하지 못합니다.

도움이 되었습니까?

해결책

In ES5, you can get a reference to global object from within strict mode via indirect eval call:

"use strict";
var global = (1,eval)('this');

Take a look at my article; particularly at this section on strict mode.

다른 팁

In global code, the thisBinding is set to the global object regardless of strict mode. That means you can pass it from there into your module IEFE:

// "use strict"; or not
(function(global) {
    "use strict";
    …
    console.log(global);
    …
}(this));

In strict mode, the way to get a reference to the global object is to assign a variable in the global object referencing itself.

That is this means the global object when in the global context, so the solution is simply:

"use strict";
var global = global || this;
(function() { global.hello = "world"; })();
console.log(hello); // Outputs 'world' as expected

This does mean that you have to pollute the global namespace with a reference to itself, but like you say, it should already have been there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top