Javascript对象枚举

时间:2017-04-21 11:48:11

标签: javascript

在控制台中放置/更改"property"this[property]的区别是什么,我相信两者都引用相同的表达式,但后者在调用函数时给出了[object,Object]。

var rockSpearguns = {
    Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
    Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
    Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
    Firefork: {barbs: 6, weight: 8, heft: "overhand"},
    "The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

rockSpearguns["listGuns"] = function(){
    for (var property in this) {
        if(this[property]["heft"]!==undefined){
            console.log("Behold! " + this[property] + ", with " +
            this[property]["heft"] + " heft!");
        }
    }
}

rockSpearguns["listGuns"]();

4 个答案:

答案 0 :(得分:2)

当您在控制台或简单脚本中访问this时,它引用window,因此与访问window范围内的变量相同。

var a = 123; // variable `a` is bound to `window`
console.log(a); // 123
console.log(window.a); // 123
console.log(this.a); // 123

但是当你在一个函数或对象中时,this引用它自己的上下文:

function test () {
    this.a = 123;
    console.log(a); // 123
    console.log(this.a); // 123
    console.log(this); // test {a: 123}
}

new test(); // to create new context for this function, we need to call `new`, otherwise it will also be `window`

console.log(typeof a); // undefined
console.log(this.a); // undefined
console.log(this); // window

有关此内容的更多信息:http://ryanmorr.com/understanding-scope-and-context-in-javascript/

答案 1 :(得分:2)

for循环内,this将是rockSpearGuns个对象。在这种情况下,this[property]将引用例如Firefork对象。您需要使用property代替this[property]

试试这个:



var rockSpearguns = {
  Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
  Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
  Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
  Firefork: {barbs: 6, weight: 8, heft: "overhand"},
  "The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};
    
rockSpearguns["listGuns"]=function(){
  for (var property in this) {
    if(this[property]["heft"]!==undefined){
      console.log("Behold! " + property + ", with " +
      this[property]["heft"] + " heft!");
    }
  }
}
    
rockSpearguns["listGuns"]();




答案 2 :(得分:2)

property将是对象beign循环("Sharpshooter""Pokepistol",...)的键,它们已经是字符串。

this[property]将是对象的值,它们都是对象。将对象与字符串连接时,通过调用其函数toString将对象强制转换为字符串。所以:

var obj = {};
var string = "Hello. I'm " + obj;

与:

相同
var obj = {};
var string = "Hello. I'm " + obj.toString();
在这种情况下,

obj.toString()将返回"[object Object]"

关于括号和点表示法,这是MDN上的文档。

答案 3 :(得分:2)

让我们一点一点地剖析它:

rockSpearguns["listGuns"]()电话是另一种说法: rockSpearguns.listGuns(); 这意味着"这个"设置为rockSpearguns对象(在呼叫站点)。

当JS尝试评估此[property]值时,它会看到此对象的值绑定到rockSpearguns和" property"是对象属性的枚举值,它是字符串(由于for-in循环)。但是,此[property]仅表示this.property(点表示法)。 在这种情况下,this.property是一个对象(神枪手等) 现在,当我们尝试连接字符串时,需要通过调用toString()方法将Sharpshooter对象转换为字符串,该方法返回[object,Object]。

相关问题