《理解 ES6》閱讀整理:函數(Functions)(五)Name Property
名字屬性(The name Property)
在JavaScript中識別函數是有挑戰性的,因為你可以使用各種方式來定義一個函數。匿名函數表達式的流行使用導致函數調試困難,在棧信息中難以找出函數名。因為這些原因,ES6為所有函數都增加了名字屬性。
選擇合適的名字(Choosing Appropriate Names)
在ES6中所有的函數都有一個合適的名字屬性。來看下面的例子:
function doSomething() { //... } var doAnotherThing = function() { //... } console.log(doSomething.name); // doSomething console.log(doAnotherThing.name); // doAnotherThing
在上面的代碼中,doSomething是一個函數聲明,name的值為doSomething。而doAnotherThing被賦值為一個匿名函數,name為doAnotherThing。
特殊情況下的名字屬性(Special Cases of the name Property)
函數聲明和函數表達式的name屬性是容易知道的,ES6確保所有的函數都有合適的名字。看下面的代碼:
var doSomething = function doSomethingElse() { //... }; var person = { get firstName() { return "Zakas" }, sayName: function() { console.log(this.name); }, }; console.log(doSomething.name); // doSomethingElse console.log(person.sayName.name); // sayName console.log(person.firstName.name); // get firstName
上面的例子中,doSomething.name的值為doSomethingElse,因為函數表達式有name屬性,并且函數表達式的name屬性優先級高于變量的name屬性。person.sayName.name的值為sayName,這個容易理解。然后person.firstName是一個getter函數,為了跟普通函數區分開,加了一個get前綴。如果是setter函數,那么要加上一個set前綴。還有幾種其他特殊情況:
var doSomething = { //... }; console.log(doSomething.bind().name); // bound doSomething console.log((new Function()).name); // anonymous
用bind創建的函數的名字屬性以bound開頭,而用Function構造函數創建的函數的名字屬性為anonymous。
函數的名字屬性主要用來調試的,不要試圖用name屬性去訪問函數。
浙公網安備 33010602011771號