访问函数'的属性

Access a function's property inside the function

本文关键字:属性 函数 访问      更新时间:2023-09-26

我希望能够在函数本身内部为函数分配属性。我不想将它分配给调用对象。所以我想要这样做的等价物:

var test  = function() {                    
    return true;         
};
test.a = 'property on a function';
alert(test.a);

相反,在将属性分配给全局对象的情况下:

var testAgain = function() {
   this.a = "this property won't be assigned to the function";
   return true;  
};
testAgain();
alert(window.a);

编辑:为了澄清,我想知道是否有这样的东西:

var test = function() {
   function.a = 'property on a function';
};
alert(test.a); // returns 'property on a function'

在不知道函数被称为test或必须执行它的情况下。我当然知道这不是有效的语法

[有没有一种方法可以在不知道函数被称为test或必须执行它的情况下设置函数的属性

强调我的。

您可以在不知道函数的全局变量名的情况下设置函数的属性,但是您必须以某种方式引用该函数。

模块模式非常适合我所能想到的:

window.test = (function () {
    //the function could be named anything...
    function testFn() {
        ...code here...
    }
    //...so long as the same name is used here
    testFn.foo = 'bar';
    return testFn;
}());
window.test.foo; //'bar'

外部闭包防止testFn在全局任何位置被访问,因此所有其他引用都必须使用window.test


这部分答案与问题的前一版本有关

最简单的方法是使用一个命名函数:

var test = function testFn() {
    testFn.foo = 'bar';
    return true;
};
test.foo; //undefined
test();
test.foo; //'bar'

更好的方法是使用模块模式,这样就不会意外地产生全局泄漏问题:

var test = (function () {
    function ret() {
        ret.foo = 'bar';
        return true;
    }
    return ret;
}());
test.foo; //undefined
test();
test.foo; //'bar'
var testAgain = function() {
    arguments.callee.a = "this property won't be assigned to the function";
    return true;  
};
testAgain();
alert(testAgain.a);​

您可以通过简单地使用名称来分配属性,如下所示:

var test = function () {
    test.a = 'a';
    return true;
};

当调用test时,将设置该属性。

演示

正如su-所说,您可以使用arguments.callee,但这被认为是非常糟糕的做法。此外,它在严格模式下无法工作。

var test = function() {
    test.a = 'a';
};

或者你可以使用原型,在这里阅读更多。