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

前端 未结 5 594
天涯浪人
天涯浪人 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 00:58

    Because name is a non-standard, non-writable property of function objects. Function declarations and named function expressions are named, while you have an anonymous function expression whose name is "".

    You probably wanted a plain object:

    var person = {
        name: "John Smith",
        age: 21,
        profession: "Web Developer"
    };
    
    0 讨论(0)
  • 2020-12-04 00:58

    You may want to use Prototype (see How does JavaScript .prototype work?) or simply turn the 'person' into a hash like so:

    var person = {};
    person.name="John Smith"; //output "John Smith"
    person.age=21; //output 21
    person.profession="Web Developer"; //output "Web Developer"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-04 01:12

    name is a special property because it gives the name of the function when defined like this:

    function abc(){
    
    }
    

    In this case name would return the string "abc". This name cannot be changed. In your case, the function does not have a name, hence the empty string.

    http://jsfiddle.net/8xM7G/1/

    0 讨论(0)
  • 2020-12-04 01:24

    The name property is set by the Function constructor and cannot be overwritten directly. If the function is declared anonymous, it will be set to an empty string.

    For example:

    var test = function test() {};
    alert(test.name); // Displays "test"
    test.name = "test2";
    alert(test.name); // Still displays "test"
    
    0 讨论(0)
提交回复
热议问题