在执行函数时,有没有办法获取Function对象?我正在为函数分配属性,并希望访问它们。“这个”没有帮助。就像是:
a.b=function(){...code...};
a.b.c=100;
我想从函数中的代码访问abc,而不知道它自己的名称。“这个”指的是 怎么能得到b?
我尝试将函数绑定到他自己的对象,但不能。
谢谢你。
我要添加此示例,我必须在几个不同的“ theString”和“ someSpecificValues”之后重复:
Object.defineProperty(theObject, theString, {get: function(...){...}.bind(theObject, someSpecificValues), configurable: true});
您可以为此使用命名函数表达式:
var a = {};
a.b = function myFunc() {
console.log(myFunc.c);
};
a.b.c = 100;
a.b();
它允许函数内部的代码访问函数本身,但不将标识符添加到封闭范围。
编辑:这是名称如何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
在无法使用命名函数表达式的情况下(例如,当您使用命名函数表达式时).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!");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句