Javascript - 这些构造函数之间有什么区别

Javascript - What is the difference between these constructor functions?

本文关键字:什么 区别 之间 构造函数 Javascript      更新时间:2023-09-26

这个构造函数有什么区别:

    var Person = function(living, age, gender) {
        this.living = living;
        this.age = age;
        this.gender = gender;
        this.getGender = function() {return this.gender};
    }

而这个:

    var Person = function Person(living, age, gender) {
        this.living = living;
        this.age = age;
        this.gender = gender;
        this.getGender = function() {return this.gender;};
    };

除了构造函数被"命名"之外,什么都没有。对于 #1,Person.name的计算结果为空字符串,对于 #2,Person.name 的计算结果为 "Person"

name 属性将在 function Person(...) 中设置。

您可以通过尝试类似的东西来查看这一点

var bar = function eigor(){}

然后看看bar.name是什么。