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

使用JavaScript获取对象实例的变量值

获取Person对象实例的变量值方法

嘿,我来帮你搞定怎么获取这个Person对象实例的变量值~其实核心逻辑很简单,就是通过实例对象直接访问对应的属性,下面分情况给你一步步演示:

第一步:先创建一个完整的Person实例

首先得把你的构造函数补全,再生成一个具体的实例,比如:

// 补全后的Person构造函数
function Person(first, last, age, gender, interests) {
  this.name = { 'first': first, 'last' : last };
  this.age = age;
  this.gen = gender;
  this.int = interests;
  this.nationality = "English";
  this.bio = function() {
    alert(`${this.name.first} ${this.name.last} is ${this.age} years old. He likes ${this.int[0]} and ${this.int[1]}.`);
  };
}

// 创建一个具体的实例对象
const myPerson = new Person('Alice', 'Smith', 28, 'female', ['reading', 'painting']);

第二步:根据属性类型获取对应值

1. 直接访问普通属性

像age、nationality这种直接挂载在实例上的基础属性,直接用实例.属性名就能拿到:

console.log(myPerson.age); // 输出:28
console.log(myPerson.nationality); // 输出:"English"
console.log(myPerson.gen); // 输出:"female"

2. 访问嵌套对象属性

name是一个嵌套的子对象,要拿到里面的first或last,需要逐层访问:

console.log(myPerson.name.first); // 输出:"Alice"
console.log(myPerson.name.last); // 输出:"Smith"

3. 访问数组类型属性

int(也就是你传入的interests)是数组,通过索引就能获取对应元素:

console.log(myPerson.int[0]); // 输出:"reading"
console.log(myPerson.int[1]); // 输出:"painting"

4. 在jQuery点击事件中访问实例属性

你提到给段落绑定了jQuery点击事件,这里要注意事件回调里的this指向的是触发事件的DOM元素,不是Person实例,所以要直接用你创建的实例变量来访问:

// 给段落绑定点击事件
$('p').click(function() {
  // 这里不能用this,要用我们提前创建好的myPerson实例
  alert(`点击触发!这个人叫${myPerson.name.first},今年${myPerson.age}岁`);
});

如果担心作用域问题,也可以用箭头函数(箭头函数的this会继承外部作用域):

$('p').click(() => {
  alert(`点击触发!这个人叫${myPerson.name.first},今年${myPerson.age}岁`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:27:06