我用这个对象方法做错了什么?

时间:2019-02-16 19:19:06

标签: javascript object

我正在尝试从一个非常基本的对象开始学习javascript对象,但我无法使其正常工作。谁能告诉我为什么最后一个console.log()返回“ undefined”而不是“ Bill”?

const firstObject = {
	name: "Bill",
	profession: "Fireman",
	age: 30,
	getInfo: function (theInfo) {
		console.log(theInfo);
		console.log(this.name);
		console.log(this.theInfo);
	},
};
firstObject.getInfo("name");

2 个答案:

答案 0 :(得分:2)

当键为[]时,使用string访问对象的属性。参见 Bracket Notation

const firstObject = {
	name: "Bill",
	profession: "Fireman",
	age: 30,
	getInfo: function (theInfo) {
		console.log(theInfo);
		console.log(this.name);
		console.log(this[theInfo]);
	},
};
firstObject.getInfo("name");

答案 1 :(得分:1)

由于console.log不是属性,您的最后一个theInfo正在记录未在对象上定义的属性。

如果要使用变量访问属性,则必须使用方括号表示法,而不是点表示法:

const firstObject = {
	name: "Bill",
	profession: "Fireman",
	age: 30,
	getInfo: function (theInfo) {
		console.log(theInfo);
		console.log(this.name);
		console.log(this[theInfo]);
	},
};
firstObject.getInfo("name");

相关问题