lengthfunction sampleFunction(a, b, c) {} console.log(sampleFunction.length); // 输出: 3'运行
namefunction namedFunction() {} console.log(namedFunction.name); // 输出: "namedFunction" const anonFunction = function() {}; console.log(anonFunction.name); // 输出: ""'运行
prototypefunction Person(name) { this.name = name; } Person.prototype.greet = function() { console.log('Hello, ' + this.name); }; const john = new Person('John'); john.greet(); // 输出: Hello, John'运行
caller (非标准)function first() { second(); } function second() { console.log(second.caller); } first(); // 输出: [Function: first]'运行
arguments (非标准,且已弃用)arguments 对象代替。function testFunc(a, b) { console.log(testFunc.arguments); } testFunc(1, 2); // 输出: [Arguments] { '0': 1, '1': 2 }'运行
JavaScript 函数可以扩展自定义属性,这让函数对象更为强大:
function add(a, b) { return a + b; } // 添加自定义属性 add.description = "This function adds two numbers"; add.version = "1.0.0"; console.log(add.description); // 输出: "This function adds two numbers" console.log(add.version); // 输出: "1.0.0"'运行
在某些情况下,你可以利用函数属性来存储状态或其他信息:
const counter = (function() { let count = 0; function counterFunc() { count += 1; return count; } counterFunc.reset = function() { count = 0; }; counterFunc.getCount = function() { return count; }; return counterFunc; })(); console.log(counter()); // 输出: 1 console.log(counter()); // 输出: 2 console.log(counter.getCount()); // 输出: 2 counter.reset(); console.log(counter()); // 输出: 1'运行
JavaScript 函数不仅仅是可调用的代码块,它们也是对象,具备一些特殊的内建属性如 length、name、prototype以及可以自定义的属性。这些属性使得函数在 JavaScript 中更加灵活和强大,允许开发者以面向对象的方式处理函数行为和状态。理解这些属性,有助于更有效地编写和使用函数。