如何在函数体中获取Function对象?

Ale*_*tri 2 javascript

有没有办法在函数执行时获取Function对象?我正在为我的函数分配属性,并希望访问它们."这个"没有用.就像是:

a.b=function(){...code...};
a.b.c=100;
Run Code Online (Sandbox Code Playgroud)

我想从函数中的代码访问abc,而不知道它自己的名字."这个"是指a.怎么能得到b?

我尝试将函数绑定到他自己的对象,但我不能.

谢谢.

我正在添加这个例子,我必须在几个不同的"theString"和"someSpecificValues"之后重复:

Object.defineProperty(theObject, theString, {get: function(...){...}.bind(theObject, someSpecificValues), configurable: true});
Run Code Online (Sandbox Code Playgroud)

JLR*_*she 6

您可以使用命名函数表达式:

var a = {};
a.b = function myFunc() {
  console.log(myFunc.c);
};
a.b.c = 100;
a.b();
Run Code Online (Sandbox Code Playgroud)

它允许函数内部的代码访问函数本身,但不会将标识符添加到封闭范围.


编辑:这是一个更详细的例子,说明名称myFunc 仅存在于函数中:

var a = {};
a.b = function myFunc() {
  console.log(myFunc.c);
};

a.b.c = 100;

a.d = function myFunc() {
  console.log(myFunc.c);
};
a.d.c = 300;

a.b();               // logs 100
a.d();               // logs 300

console.log(typeof myFunc);    // logs "undefined"

// create a myFunc variable
var myFunc = function() {
  console.log("nooooooo!!!!");
};

a.b();       // STILL logs 100. the myFunc variable in this scope
             //    has no effect on the myFunc name that a.b uses

function callFunc(theFunc) {
    theFunc();
}

callFunc(a.d);       // STILL logs 300

//  ===========================

function returnNamedFunction () {
    return function myFunc() {
        console.log(myFunc.c);
    };
}

 var iGotAFunction = returnNamedFunction();
 iGotAFunction.c = 700;

 iGotAFunction();          // logs 700
Run Code Online (Sandbox Code Playgroud)

在您不能使用命名函数表达式的情况下,例如当您使用.bind()它时,IIFE就足以满足大部分时间:

var myObj = {};

myObj.theFunc = (function () {
    var f = function (arg1, arg2) {
        console.log(this.theProp);
        console.log(arg1);
        console.log(arg2);
        console.log(f.lista);
    }.bind(myObj, "A!");
    return f;
})();

myObj.theProp = "B!";
myObj.theFunc.lista = [1, 2, 3];
myObj.theFunc("C!");
Run Code Online (Sandbox Code Playgroud)