简体   繁体   English

获取JavaScript中的函数体

[英]Get body of function in JavaScript

i am trying to get the body of a function in JavaScript but am unable to do so. 我正在尝试获取JavaScript函数的主体,但无法这样做。 Let's say I wanted to see the function body of the native toUpperCase() function of the String object: 假设我想查看String对象的本机toUpperCase()函数的函数体:

document.write(String.prototype.toUpperCase.toString()); 
// returns function toUpperCase() { [native code] }

I tried this in Safari, Chrome, Firefox, all return the same thing. 我在Safari,Chrome,Firefox中尝试过此操作,但都返回相同的结果。 How do I access what that [native code] contents is? 如何访问[本机代码]内容是什么?

* update * *更新*

The reason I stumbled onto this question, is because I was trying to do the following: 我偶然发现此问题的原因是因为我尝试执行以下操作:

If I have two functions, one of which I want to invoke on the other, I want to access the first function's return value in the second, so that I can do function1().function2(). 如果我有两个函数,我想在另一个函数上调用它,那么我想在第二个函数中访问第一个函数的返回值,以便可以执行function1()。function2()。 For example: 例如:

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

So I wanted to see how a function like toUpperCase() accesses the return value of a function it is invoked on. 所以我想看看像toUpperCase()这样的函数如何访问对其调用的函数的返回值。

You can add a function to String.prototype , then you can "chain" your function calls. 您可以将一个函数添加到String.prototype ,然后可以“链接”您的函数调用。

String.prototype.makeUpperCase = function(){
  // 'this' is the string that 'makeUpperCase' was called on
  return this.toUpperCase();
};

var y = returnValue().makeUpperCase();

Chaining works by having the functions be part of the object, String.prototype in this case. 链接通过使函数成为对象(在这种情况下为String.prototype一部分而起作用。 So, when you return that object (a string), you can call another function on it ("chaining"). 因此,当您返回该对象(字符串)时,可以在其上调用另一个函数(“链接”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM