You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript原型问题:属性值始终为undefined

问题排查与解决:原型属性无法正确获取实例属性值

问题原因

你给Person.prototype.FullName直接赋值时,代码执行到这一行的this指向的是全局对象(浏览器环境下为window),而非Person的实例。全局对象中不存在firstName和lastName属性,所以拼接结果就是undefined undefined。

解决方案

提供三种可行的解决方式,按需选择:

1. 原型getter属性(推荐)

通过Object.defineProperty给原型添加getter,访问FullName时会动态计算值,且this会指向当前实例:

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

// 定义原型getter
Object.defineProperty(Person.prototype, 'FullName', {
  get: function() {
    return this.firstName + ' ' + this.lastName;
  }
});

var person = new Person("MyName","MySirname",14,"Black")
console.log(person.FullName) // 输出 MyName MySirname

这种方式的优势是:访问形式和普通属性一致,后续修改实例的firstName或lastName,FullName会自动同步更新。

2. 构造函数内直接添加属性

在实例创建时直接计算FullName并挂载到实例上:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  // 实例创建时直接赋值
  this.FullName = this.firstName + ' ' + this.lastName;
}

var person = new Person("MyName","MySirname",14,"Black")
console.log(person.FullName) // 输出 MyName MySirname

注意:这种方式下,后续修改实例的firstName或lastName,FullName不会自动更新,需要重新赋值。

3. 原型方法

把FullName做成原型方法,调用时执行计算:

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

Person.prototype.getFullName = function() {
  return this.firstName + ' ' + this.lastName;
}

var person = new Person("MyName","MySirname",14,"Black")
console.log(person.getFullName()) // 输出 MyName MySirname

这种方式适合需要额外参数或更复杂逻辑的场景,缺点是需要以方法调用的形式(加括号)获取值。

内容的提问来源于stack exchange,提问作者C Sharper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:40:55