Embed scripts in an existing function?

This function is built into the page, and I cannot change the original .js file:

cool.lol = function () {

    // contents here

}

Is there a way to add this function to some of my own scripts?

Like this:

cool.lol = function () {

    // contents here

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

Or do I have a way to detect that the function is complete, so I can start something after it?

+3
source share
5 answers

Here is the description below . Updated to use closure and remove the need for a temporary variable.

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

//let 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();​
+10
source

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();​
+1
source

:

// 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/

+1

, :

 //let 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();​
+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/

+1

All Articles