函数
函数名就是指向函数的指针。意味着一个函数可以有多个名称。
function sum(num1,num2){
return num1+num2;
}
console.log(sum(10,10)); //20
let anotherSum = sum;
console.log(anotherSum(10,10)); //20
sum=null;
console.log(anotherSum(10,10)); //20
使用不带括号的函数名会访问函数指针,而不会执行函数。此时anotherSum
和sum
都指向同一个函数。把sum
设置成null
之后,就切断了它与函数的联系,但是anotherSum
还是可以照常使用。
ES6
所有的函数都会暴露一个只读的name
属性,保存的就是一个函数标识符。一个字符串化的变量名。即使函数没有名称,也会如实显示成空字符串。如果它是使用Function
函数创建的,则会标识成anonymous
function foo(){}
let bar = function (){}
let baz = ()=>{}
console.log(foo.name);//foo
console.log(bar.name);//bar
console.log(baz.name);//baz
console.log((()=>{}).name);//空字符串
console.log((new Function()).name);//anonymous
如果函数是一个获取函数、设置函数,或者使用bind()
实例化,那么标识符前面会加上一个前缀。
function foo(){}
console.log(foo.bind(null).name);//bound foo
let dog={
years:1,
get age(){
return this.years;
},
set age(value){
this.years=value;
}
}
console.log(Object.getOwnPropertyDescriptor(dog,'age').get.name);//get age
console.log(Object.getOwnPropertyDescriptor(dog,'age').set.name);//set age
- 本文链接:https://archer-lan.github.io/2023/11/20/JS-%E5%87%BD%E6%95%B0/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。