當定義和呼叫函式時,JavaScript 函式物件會自動具有一些特定的屬性,以下是一些常見的屬性和方法,
1. arguments : arguments 是一個類陣列物件,它包含了函式呼叫時傳遞的引數,它允許你在函式內部訪問傳遞給函式的引數串列,即使在函式定義時未明確宣告這些引數,可以通過索引訪問 arguments 物件中的引數值,也可以使用 arguments.length 獲取傳遞的引數個數,
function exampleFunc(a, b) { console.log(arguments[0]); // 訪問第一個引數 console.log(arguments.length); // 引數的個數 } exampleFunc(1, 2, 3); // 1,3
注意:在es6開始,推薦使用剩余引數或者使用命名引數來代替使用 arguments 物件,
2. length : length 屬性回傳函式宣告時的形引數量,即函式期望接收的引數個數,它表示函式定義時定義的形參個數,不包括剩余引數,
function exampleFunc(a, b, c) { // 函式體 } console.log(exampleFunc.length); // 3
3. name : name 屬性回傳函式的名稱,對于具名函式,它回傳函式的實際名稱,
function namedFunction() { // 函式體 } const anonymousFunction = function() { // 函式體 } console.log(namedFunction.name); // namedFunction console.log(anonymousFunction.name); // anonymousFunction
這些屬性使得函式物件在運行時具有額外的元資料,可以根據需要訪問這些屬性來獲取有關函式的資訊,例如函式的引數、引數個數和名稱,這些屬性在撰寫靈活和通用的函式時非常有用,
4. caller : caller 屬性回傳一個呼叫當前函式的函式參考,如果當前函式是在全域作用域中被呼叫的,那么 caller 將回傳 null ,該屬性在嚴格模式下被禁用,
function outerFunc() { innerFunc(); } function innerFunc() { console.log(innerFunc.caller); // outerFunc } outerFunc();
5. prototype : prototype 屬性允許你向函式物件添加新的屬性和方法,它用于創建基于原型繼承的物件,
function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log("Hello, " + this.name); }; const person = new Person("John"); person.sayHello(); // Hello, John
6. bind() : bind() 方法回傳一個新的函式,該函式在呼叫時將指定的 this 值系結到提供的引數,用于創建函式的新實體并永久性地系結函式的背景關系,
const obj = { name: "John", greet: function() { console.log("Hello, " + this.name); } }; const boundFunc = obj.greet.bind(obj); boundFunc(); // Hello, John
類似的還有 apply() 、 call() 、 toString() 等,
7. constructor : constructor 屬性回傳創建函式物件的原型物件的參考,
function Person(name) { this.name = name; } const person = new Person("John"); console.log(person.constructor); // 輸出:Person
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/552871.html
標籤:其他
上一篇:網站都變灰了,幾行代碼可以實作
下一篇:返回列表
