Javascript对象枚举
在控制台中放置/更改"property"
与this[property]
有什么区别,我相信它们都是指同一个表达式,但是当我调用函数时,后者会给我[object,Object]。Javascript对象枚举
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"]();
property
将循环对象beign(3210,"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的文档。
当在控制台或一个简单的脚本中访问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/
但他们是一样的,除了在控制台,不是吗? –
它可以通过'bind'方法改变,但通常当你不在一个函数或对象内时,'this'将引用'window'。 –
谢谢,我会稍后再试。 –
里面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"]();
如果我没有弄错,它不是for循环,而是for循环:)。此外,为什么当您尝试在JS Bin这样的站点中调试它时,总是需要在访问对象和对象属性时使用括号和点符号的组合? –
选中此项:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors 如果您使用变量来标识对象的属性,那么您需要使用括号。 – kotapeter
让我们来剖析一点一滴:
rockSpearguns["listGuns"]()
电话是另一种说法: rockSpearguns.listGuns(); 这意味着“this”的上下文被设置为rockSpearguns对象(在呼叫站点)。
当JS试图评估这个[property]值时,它看到这个对象的值被绑定到rockSpearguns,而“property”是对象属性的字符串的枚举值(由于for-in循环)。但是,这[属性]仅仅意味着this.property(点符号)。 在这种情况下,this.property是一个对象(Sharpshooter等) 现在,当我们试图连接字符串时,需要通过调用返回[object,Object]的toString()方法将Sharpshooter对象转换为字符串。
你问这个[“property”]'和'this [property]'有什么区别? –
nope,属性和这[属性]在控制台 –