gpt4 book ai didi

javascript - 通过 this 使用方法访问对象

转载 作者:行者123 更新时间:2023-11-28 20:25:30 24 4
gpt4 key购买 nike

你能帮我解决这个代码吗?

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”登录控制台。

感谢您的帮助。

最佳答案

所以,这是执行您想要执行的操作的代码:

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));

关于javascript - 通过 this 使用方法访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17498967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com