我试图在JavaScript中获得函数的主体,但我无法这样做。假设我想查看String对象的本机toUpperCase()函数的函数体:
document.write(String.prototype.toUpperCase.toString());
// returns function toUpperCase() { [native code] }
我在Safari, Chrome, Firefox中尝试了这个,都返回相同的东西。我如何访问[本机代码]内容?
* update *
我偶然发现这个问题的原因是因为我正试图做以下事情:
如果我有两个函数,其中一个我想在另一个上调用,我想在第二个函数中访问第一个函数的返回值,这样我就可以执行function1().function2()。例如:
// create a global function that returns a value
function returnValue() {
x = "john";
return x;
}
// create a function that converts that value to uppercase
function makeUpperCase(){
return this.toUpperCase();
// "this" obviously doesn't work, but "this" is where I wanted to
// access the return value of a function I'm invoking makeUpperCase() on.
}
所以我想看看像toUpperCase()这样的函数是如何访问调用它的函数的返回值的
您可以添加一个函数到String.prototype
,然后您可以"链接"您的函数调用。
String.prototype.makeUpperCase = function(){
// 'this' is the string that 'makeUpperCase' was called on
return this.toUpperCase();
};
var y = returnValue().makeUpperCase();
链接的工作原理是让函数成为对象的一部分,在本例中是String.prototype
。所以,当你返回那个对象(一个字符串)时,你可以在它上面调用另一个函数("chaining")。