通过此方法使用方法访问对象

时间:2013-07-06 02:08:39

标签: javascript

你可以帮我解决一下这段代码吗?

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 个答案:

答案 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)

notebookmac的内在因素,因此您无法在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)

有一些事情要做。

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