我們知道,Javascript中函數有靜態函數、成員函數和實例化對象的成員函數之分,這些函數的實現存在正常函數和匿名函數的區分。所以在我們Hook成員時,我們要對這些情況兼而顧之。
例如對與下列函數Hook調用,預想產生如下的輸出:
//全局函數無參數
function Method1(){
alert('Method1');
}
Method1.hook(function()
{
alert('befor Method1');
return true;
},
function()
{
alert('after Method1');
}
);
Method1();
/* 輸出
befor Method1
Method1
after Method1
*/
alert('-----------------');
//全局函數有參數
function Method2(name){
alert('Method2 with ' + name);
}
Method2.hook(function(name)
{
alert('befor Method2 with ' + name);
return true;
},
function()
{
alert('after Method2 ');
}
);
Method2('evlon');
/* 輸出
befor Method2 with evlon
Method2 with evlon
after Method2
*/
alert('-----------------');
//Hook字符串的toString 函數
String.prototype.toString.hook(String.prototype, function()
{
alert('befor string.toString');
return true;
});
var s = "return s";
alert(s.toString());
/* 輸出
befor string.toString
return s
*/
alert('-----------------');
//Hook 系統已有全局函數parseInt
parseInt.hook(function()
{
alert('befor parseInt');
return true;
});
alert(parseInt('5'));
/* 輸出
befor parseInt
5
*/
alert('-----------------');
//Hook 所有數組對象的join 方法
Array.prototype.join.hook(Array.prototype, function(span)
{
alert('befor Array.prototype.join separator ' + span);
return true;
});
alert([3,5,6].join(','));
/* 輸出
befor Array.prototype.join separator ,
3,5,6
*/
alert('-----------------');
var list = [3, 5, 6];
//Hook list 這個實例數組對象的join 方法
list.join.hook(list, function(span)
{
alert('befor list.join separator ' + span);
return true;
});
alert(list.join(','));
/* 輸出
befor list.join separator ,
befor Array.prototype.join separator ,
3,5,6
*/
alert('-----------------');
var list2 = [3, 5, 6, 7];
// 此處調用不會產生befor list.join separator ,
alert(list2.join(','));
/* 輸出
befor Array.prototype.join separator ,
3,5,6,7
*/
alert('-----------------');
//自定義類
function People() {
//成員函數帶參數
this.getName = function(name) {
alert('in getName with ' + name);
return 'return evlon';
}
}
var p = new People();
var p2 = new People();
//這里我們只Hook實例p2 的函數調用
p2.getName.hook(p2, 'getName2',
function(name) {
alert('befor getName2 with ' + name);
return true;
},
function() {
alert('after getName2');
}
);
p2.getName.hook(p2,
function(name) {
alert('befor getName with ' + name);
return true;
},
function() {
alert('after getName');
}
);
//因為只Hook了P2, 對這個調用無影響
alert(p.getName('argName'));
/* 輸出
in getName with argName
return evlon
*/
alert('-----------------');
alert(p2.getName('argName'));
/* 輸出
befor getName with argName
in getName with argName
after getName
return evlon
*/
alert('-----------------');
alert(p2.getName2('argName2'));
/* 輸出
befor getName2 with argName2
in getName with argName2
after getName2
return evlon
*/