![](/img/trans.png)
[英]Accessing parent prototype method via child object like a normal child method
[英]Accessing object using method via this
你能帮我这个代码吗?
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));
notebook
是mac
内部的,因此您不能在console.log(mac.get_product(notebook));
上访问它console.log(mac.get_product(notebook));
看一下这篇文章: http : //javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
就像get_product
函数一样, notebook
参数也在变量mac中定义-因此您需要将其称为mac.notebook
。
有一些事情要解决。
没有“ this.kind”这样的东西(我想你的意思是“ this.notebook”)。
var mac = { notebook: "macbook", desktop: "imac", get_product: function (kind) { return this.notebook; } } console.log(mac.get_product(mac.notebook));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.