var mac = {
notebook: "macbook",
desktop: "imac",
get_product: function (kind) {
return this.kind;
}
}
console.log(mac.get_product(notebook)); //ReferenceError: notebook is not defined
我希望“macbook”能够登录控制台。
感谢您提供帮助。
答案 0 :(得分:3)
所以,这就是你要做的事情的代码:
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));
答案 1 :(得分:0)
notebook
是mac
的内在因素,因此您无法在console.log(mac.get_product(notebook));
看一下这篇文章:http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
答案 2 :(得分:0)
就像get_product
函数一样,notebook
参数也在变量mac中定义 - 因此您需要将其称为mac.notebook
。
答案 3 :(得分:0)
有一些事情要做。
没有'this.kind'这样的东西(我猜你的意思是'this.notebook')。
var mac = {
notebook: "macbook",
desktop: "imac",
get_product: function (kind) {
return this.notebook;
}
}
console.log(mac.get_product(mac.notebook));