0

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

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

感谢您的帮助。

4

4 回答 4

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));
于 2013-07-06T02:12:41.160 回答
0

这有几件事。

  1. 没有“笔记本”之类的东西(它是“mac.notebook”),
  2. 没有“this.kind”这样的东西(我想你的意思是“this.notebook”)。

    var mac = {  
        notebook: "macbook",  
        desktop: "imac",  
        get_product: function (kind) {  
            return this.notebook;  
        }  
    }  
    
    console.log(mac.get_product(mac.notebook)); 
    
于 2013-07-06T02:19:28.590 回答
0

notebook是内部的,mac所以你不能访问它console.log(mac.get_product(notebook));

看看这篇文章:http: //javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

于 2013-07-06T02:12:21.697 回答
0

就像get_product函数一样,notebook参数也在变量 mac 中定义 - 所以你需要将它称为mac.notebook.

于 2013-07-06T02:12:40.847 回答