3

この関数はページに組み込まれており、元の .js ファイルを変更することはできません。

cool.lol = function () {

    // contents here

}

この関数を独自のスクリプトに追加する方法はありますか?

このような:

cool.lol = function () {

    // contents here

    // i would like to add my own stuff here!!!
}

または、関数が実行されたことを検出して、その後に何かを実行できるようにする方法はありますか?

4

5 に答える 5

10

これは、次のデモです。クロージャーを使用して一時変数の必要性をなくすように更新されました。

//your cool with lol
var cool = {
    lol: function() {
        alert('lol');
    }
}

//let's have a closure that carries the original cool.lol
//and returns our new function with additional stuff

cool.lol = (function(temp) { //cool.lol is now the local temp
    return function(){       //return our new function carrying the old cool.lol
        temp.call(cool);     //execute the old cool.lol
        alert('bar');        //additional stuff
    }
}(cool.lol));                //pass in our original cool.lol

cool.lol();
cool.lol();​
于 2012-05-25T02:39:25.937 に答える
1

パブリックスコープを汚染する変数を作成せずに:

 //let's have your cool namespace
var cool = {
    lol: function() {
        alert('lol');
    }
}

//temporarily store
cool.lol_original = cool.lol;

//overwrite
cool.lol = function() {
    this.lol_original(); //call the original function
    alert('bar');    //do some additional stuff
}

cool.lol();​
于 2012-05-25T02:48:31.443 に答える
1

http://jsfiddle.net/Pcxn5/1/

// original definition which you can't touch
var cool = {
    lol: function() {
        alert("test");
    }
}
//

// your script
var ori = cool.lol;
cool.lol = function() {
    ori();
    alert('my test');
}

cool.lol();​
于 2012-05-25T02:40:13.553 に答える
1

関数をオーバーライドできます。

// The file you can't touch has something like this
var cool = {};
cool.lol = function () {
    console.log("original");
}

// Keep a copy of the original function.
// Override the original and execute the copy inside
var original = cool.lol;
cool.lol = function () {
    original();
    console.log("modified");
}

// Call
cool.lol();​ // logs "original", then "modified".

http://jsfiddle.net/K8SLH/

于 2012-05-25T02:41:13.370 に答える
1

JavaScript でできること

  • 関数のコードを文字列として取得する
  • 文字列にコードを指定して新しい関数を作成する

すべてのオブジェクトにはtoString()メソッドがあります。関数の場合、コードを返します (オーバーライドされない限り)。

cool.lol.toString();

戻りますfunction() { // contents here }

この文字列から関数の本体を抽出しましょう。直後に始まり{、最後の を除くすべてが含まれます}

var code = cool.lol.toString();
var body = code.substring(code.indexOf('{') + 1, code.length - 1);

次に、さらにものを追加します

var newBody = body + '// i would like to add my own stuff here!!!';

コンストラクターを使用して新しい関数を作成しますFunction

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

cool.lol = new Function(newBody);

もちろん、新しい関数が引数も保持する必要がある場合は、さらに作業が必要です (関数コードから引数を解析して、Functionコンストラクターにパラメーターとして渡す必要があります)。簡単にするために、この場合、関数には引数がないと仮定しました。

実装例:

http://jsfiddle.net/QA9Zx/

于 2012-05-25T02:53:08.590 に答える