欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript常見的函數(shù)中的屬性與方法總結(jié)

 更新時間:2023年05月19日 10:13:58   作者:施主來了  
當(dāng)定義和調(diào)用函數(shù)時,JavaScript?函數(shù)對象會自動具有一些特定的屬性,本文為大家總結(jié)了一些常見的屬性和方法,感興趣的小伙伴可以了解一下

當(dāng)定義和調(diào)用函數(shù)時,JavaScript 函數(shù)對象會自動具有一些特定的屬性,以下是一些常見的屬性和方法。

1.arguments

arguments 是一個類數(shù)組對象,它包含了函數(shù)調(diào)用時傳遞的參數(shù)。它允許你在函數(shù)內(nèi)部訪問傳遞給函數(shù)的參數(shù)列表,即使在函數(shù)定義時未明確聲明這些參數(shù)??梢酝ㄟ^索引訪問 arguments 對象中的參數(shù)值,也可以使用 arguments.length 獲取傳遞的參數(shù)個數(shù)。

function exampleFunc(a, b) {
  console.log(arguments[0]); // 訪問第一個參數(shù)
  console.log(arguments.length); // 參數(shù)的個數(shù)
}

exampleFunc(1, 2, 3); // 1,3

注意:在es6開始,推薦使用剩余參數(shù)或者使用命名參數(shù)來代替使用 arguments 對象。

2.length

length 屬性返回函數(shù)聲明時的形參數(shù)量,即函數(shù)期望接收的參數(shù)個數(shù)。它表示函數(shù)定義時定義的形參個數(shù),不包括剩余參數(shù)。

function exampleFunc(a, b, c) {
  // 函數(shù)體
}

console.log(exampleFunc.length); // 3

3.name

name 屬性返回函數(shù)的名稱。對于具名函數(shù),它返回函數(shù)的實際名稱。

function namedFunction() {
  // 函數(shù)體
}

const anonymousFunction = function() {
  // 函數(shù)體
}

console.log(namedFunction.name); // namedFunction
console.log(anonymousFunction.name); // anonymousFunction

這些屬性使得函數(shù)對象在運行時具有額外的元數(shù)據(jù),可以根據(jù)需要訪問這些屬性來獲取有關(guān)函數(shù)的信息,例如函數(shù)的參數(shù)、參數(shù)個數(shù)和名稱。這些屬性在編寫靈活和通用的函數(shù)時非常有用。

4.caller

caller 屬性返回一個調(diào)用當(dāng)前函數(shù)的函數(shù)引用。如果當(dāng)前函數(shù)是在全局作用域中被調(diào)用的,那么 caller 將返回 null。該屬性在嚴(yán)格模式下被禁用。

function outerFunc() {
  innerFunc();
}

function innerFunc() {
  console.log(innerFunc.caller); // outerFunc
}

outerFunc();

5.prototype

prototype 屬性允許你向函數(shù)對象添加新的屬性和方法。它用于創(chuàng)建基于原型繼承的對象。

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() 方法返回一個新的函數(shù),該函數(shù)在調(diào)用時將指定的 this 值綁定到提供的參數(shù),用于創(chuàng)建函數(shù)的新實例并永久性地綁定函數(shù)的上下文。

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 屬性返回創(chuàng)建函數(shù)對象的原型對象的引用。

function Person(name) {
  this.name = name;
}

const person = new Person("John");

console.log(person.constructor); // 輸出:Person

到此這篇關(guān)于JavaScript常見的函數(shù)中的屬性與方法總結(jié)的文章就介紹到這了,更多相關(guān)JavaScript函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論