Accessing function object's properties from inside the function body
Functions in javascript is also an object and can have properties. So is there any way to access its properties from inside its own function body?
like this
var f = function() {
console.log(/*some way to access f.a*/);
};
f.a = 'Test';
f(); //should log 'Test' to console
arguments.callee
是函数本身,不受函数名称的影响。
var f = function() {
console.log(arguments.callee.a);
};
f.a = 'Test';
f();
You could just use this:
console.log(f.a);
If f
is executed, f()
, before fa = 'Test';
you will get undefined
in the console, since there isn't any property with name/key a
be defined. After fa = 'Test';
being executed, the name/key a
will be defined on f and the corresponding value would be 'Test'
. Hence, executing later on the function f
, the value 'Test'
would be the output to the console.
这样做的经典方法是将函数绑定到自身,然后可以通过this
方法访问自己的属性:
var f = function() {
console.log(this.a); // USE "THIS" TO ACCESS PROPERTY
};
f.a = 'Test';
f = f.bind(f); // BIND TO SELF
f(); // WILL LOG 'Test' TO CONSOLE
链接地址: http://www.djcxy.com/p/83020.html
下一篇: 从函数体内部访问函数对象的属性