Created
May 29, 2013 03:26
-
-
Save hongru/5667775 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function connect(scope, fnFrom, fnTo) { | |
"use strict" | |
var objFn = fnFrom.split('.');//处理传入的函数名 | |
var deepth = objFn.length; | |
var scope = scope || window; | |
var j = deepth,i=j; | |
var _obj = scope,__obj=_obj ; | |
while (i > 0) {//以window.console.log为例,这里利用迭代最终拿到log | |
_obj = _obj[objFn[deepth - i]]; | |
i -= 1; | |
}; | |
var t = function () { | |
var ret = _obj.apply(this, arguments);//此时this指向console 注意console.log log函数上下文必须在console那里,否则会报错 | |
fnTo.apply(this, arguments); | |
return ret; | |
} | |
while (j > 1) {//仍然利用迭代,找出window.console.log前一级window.console的引用 | |
__obj = __obj[objFn[deepth - j]]; | |
j -= 1; | |
} | |
__obj[objFn[deepth - 1]] = t;//覆盖window.console.log | |
} | |
function unconnect(scope,fn){ | |
var objFn = fn.split('.');//处理传入的函数名 | |
var deepth = objFn.length; | |
var scope = scope || window; | |
var j = deepth,i=j; | |
var _obj = scope; | |
while (i > 0) {//以window.console.log为例,这里利用迭代最终拿到log | |
_obj = _obj[objFn[deepth - i]]; | |
i -= 1; | |
}; | |
delete _obj | |
} | |
function publishConsole(inner){ | |
document.write(inner) | |
} | |
//start | |
unconnect(window,'console.log') | |
connect(window,'console.log',publishConsole) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment