Monday, May 2, 2011

Extending javascript functions

Method 1/

function Animal(name){
    this.name = name;
}
Animal.prototype.talk = function(){
    console.log("My name is "+this.name);
}
var a = new Animal("Brendan Eich");
a.talk();
var json = '{name: "Tim Berners-Lee"}'
var b = eval(b);
$.extend(b, Animal.prototype);
b.talk();

Method 2/

// declare function foo
var foo = function (a) { alert(a); };
// modify function foo
foo = new Function (
  "a",
  foo.toSource()
    .replace("alert(a)", "alert('function modified - ' + a)")
    .replace(/^function[^{]+{/i,"")  // remove everything up to and including the first curly bracket
    .replace(/}[^}]*$/i, "")  // remove last curly bracket and everything after
);
 
Method 3/
function m1(){
  alert('Initial function')
} 
webBrowse1.Navigate(@"javascript:m1=new function(alert('Replace after.'))");
 

No comments:

Post a Comment

Subscribe