【问题标题】:Javascript prototype - Variable remains undefinedJavascript 原型 - 变量仍未定义
【发布时间】:2023-01-20 17:17:49
【问题描述】:

我有以下代码片段 -

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

var person=new Person("MyName","MySirname",14,"Black")
Person.prototype.FullName=this.firstName+" "+this.lastName
console.log(person.FullName)

在这个示例代码中,这里是undefined undefined;而我期望 - MyName MySirname

【问题讨论】:

    标签: javascript jquery reactjs


    【解决方案1】:

    原因是 Person.prototype.FullName = this.firstName + " " + this.lastName 这行是在调用 Person 构造函数时执行的,此时 this 的值是全局对象。因此,this.firstName 和 this.lastName 的值是未定义的,因此结果是未定义的。

    设置 FullName 属性的正确方法是使用传递给构造函数的参数,如下所示:

    Person.prototype.FullName = function() {
      return this.firstName + " " + this.lastName;
    };
    

    然后您可以像这样在 person 对象上调用 FullName 方法:

    console.log(person.FullName()); // MyName MySirname
    

    【讨论】:

    • 或者使用 Object.defineProperty(Person.prototype, "FullName"... 如果你希望 FullName 像普通属性一样被访问
    • 它不知何故仍然给我未定义 - playcode.io/1081509
    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多