所以,这就是你想要做的代码:
var mac = {
notebook: "macbook",
desktop: "imac",
get_product: function (kind) {
return this[kind];
}
}
console.log(mac.get_product('notebook'));
查看您的原始代码:
var mac = {
notebook: "macbook",
desktop: "imac",
get_product: function (kind) {
// this.kind means mac.kind. You haven't defined mac.kind.
// return this.kind;
// instead, you want to look up the value of the property defined
// at kind.
// [] allow you to dynamically access properties in JavaScript
// this["<something>"] means "get me the property named <something>
// but because the contents of [] are determined before the overall
// expression, this is the same as return this["<something>"];
// var prop = "<something>"; return this[prop];
return this[kind];
}
}
// notebook (without quotes) is interpreted as a variable, but there is no
// variable by the name "notebook".
console.log(mac.get_product(notebook));