《理解 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属性去访问函数。

原文地址:https://www.cnblogs.com/xfshen/p/5991136.html