IT

프로그래밍 방식으로 자바 펼쳐 함수에 코드 추가

lottoking 2020. 8. 7. 07:47
반응형

프로그래밍 방식으로 자바 펼쳐 함수에 코드 추가


기존의 JS 코드를 수정하지 않고 기존 JS 라이브러리를 사용자 지정하려고합니다. 이 코드는 외부 액세스 할 수있는 몇 개의 JS 파일에로드 파일, 내가 원하는 것은 전체를 두 번째 파일에 복사하여 넣지 않고 원본에 포함 된 함수 중 하나를 변경하는 것입니다.
예를 들어, 제한 해제 JS에는 다음과 같은 기능이있을 수 있습니다.

var someFunction = function(){
    alert("done");
}

어떻게 든 그 함수에 JS 코드를 추가하거나 붙일 수 있기 때문입니다. 그 이유는 주로 원래 원래입니다. JS에서 함수가 꽤 방대하고 JS가 업데이트 할 때 내가 쓰는 함수가 구식이기 때문입니다.

확신 할 수 없다고 확신하지 못하지만 확인해야한다고 생각했습니다.


someFunction적으로 사용 전역 가능한 경우 함수를 캐시하고 직접 만들고 호출하도록 할 수 있습니다.

그래서 이것이 원본이라면 ...

someFunction = function() {
    alert("done");
}

당신은 할 것입니다 ...

someFunction = (function() {
    var cached_function = someFunction;

    return function() {
        // your code

        var result = cached_function.apply(this, arguments); // use .apply() to call it

        // more of your code

        return result;
    };
})();

여기 바이올린이 있습니다


.apply캐시 된 함수를 호출하는 데 사용 합니다. 전달 된 인수를 통해 전달되는 인수를 유지 하고 this얼마나 많은 인수가 있었는지에 관계를 유지할 수 있습니다.


먼저 실제 함수를 변수에 저장합니다.

var oldFunction = someFunction;

그런 다음 자신을 정의하십시오.

someFunction = function(){
  // do something before
  oldFunction();
  // do something after
};

코드를 호출하는 함수를 만든 다음 해당 함수를 호출 할 수 있습니다.

var old_someFunction = someFunction;
someFunction = function(){
    alert('Hello');
    old_someFunction();
    alert('Goodbye');
}

함수를 업데이트 할 수 있는지 모르겠지만 참조 방법에 따라 그 자리에 새 함수를 만들 수 있습니다.

var the_old_function = someFunction;
someFunction = function () {
    /* ..My new code... */
    the_old_function();
    /* ..More of my new code.. */
}


또한. 로컬 비용을 변경 요청 함수를 다시 선택합니다. 예를 들면 다음과 같습니다.

var t = function() {
    var a = 1;
};

var z = function() {
    console.log(a);
};

지금

z() // => log: undefined

그때

var ts = t.toString(),
    zs = z.toString();

ts = ts.slice(ts.indexOf("{") + 1, ts.lastIndexOf("}"));
zs = zs.slice(zs.indexOf("{") + 1, zs.lastIndexOf("}"));

var z = new Function(ts + "\n" + zs);

z() // => log: 1

그러나 이것은 가장 간단한 예일뿐입니다. 인수, 주석 및 반환 값을 처리하려면 여전히 많은 작업이 필요합니다. 또한 여전히 많은 함정이 있습니다.
toString | 슬라이스 | indexOf | lastIndexOf | 새로운 기능


프록시 패턴 (user1106925에서 사용됨)은 함수 안에 넣을 수 있습니다. 내가 아래에 작성한 것은 전역 범위에 있지 않은 함수와 프로토 타입에서도 작동합니다. 다음과 같이 사용합니다.

extender(
  objectContainingFunction,
  nameOfFunctionToExtend,
  parameterlessFunctionOfCodeToPrepend,
  parameterlessFunctionOfCodeToAppend
)

아래 스 니펫에서 test.prototype.doIt ()을 확장하는 함수를 사용하는 것을 볼 수 있습니다.

// allows you to prepend or append code to an existing function
function extender (container, funcName, prepend, append) {

    (function() {

        let proxied = container[funcName];

        container[funcName] = function() {
            if (prepend) prepend.apply( this );
            let result = proxied.apply( this, arguments );
            if (append) append.apply( this );
            return result;
        };

    })();

}

// class we're going to want to test our extender on
class test {
    constructor() {
        this.x = 'instance val';
    }
    doIt (message) {
        console.log(`logged: ${message}`);
        return `returned: ${message}`;
    }
}

// extends test.prototype.doIt()
// (you could also just extend the instance below if desired)
extender(
    test.prototype, 
    'doIt', 
    function () { console.log(`prepended: ${this.x}`) },
    function () { console.log(`appended: ${this.x}`) }
);

// See if the prepended and appended code runs
let tval = new test().doIt('log this');
console.log(tval);

참고 URL : https://stackoverflow.com/questions/9134686/adding-code-to-a-javascript-function-programmatically

반응형