Why can't I set a JavaScript function's name property?

前端 未结 5 604
天涯浪人
天涯浪人 2020-12-04 00:37

I am learning JavaScript and read that functions are like objects and can have properties set like this:

var person = function(){
}
person.name=\"John Smith\         


        
5条回答
  •  难免孤独
    2020-12-04 01:06

    You can change the name property!

    The Function.name property is configurable as detailed on MDN.

    Since it's configurable, we can alter its writable property so it can be changed. We need to use defineProperty to do this:

    var fn = function(){};
    Object.defineProperty(fn, "name", {writable:true});
    // now you can treat it like a normal property:
    fn.name = "hello";
    console.log(fn.name); // outputs "hello"
    

提交回复
热议问题