gpt4 book ai didi

javascript - 在循环内调用对象的方法

转载 作者:行者123 更新时间:2023-11-29 16:13:33 25 4
gpt4 key购买 nike

为什么不能在循环中使用点符号访问对象属性?

var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"}
};
function listGuns(guns) {
for ( var gun in guns ) {
console.log("Behold! " + gun + ", with " + gun.heft + " heft!");
}
}
listGuns(rockSpearguns);

这会产生这个输出:

Behold! Sharpshooter, with undefined heft!
Behold! Pokepistol, with undefined heft!

但是,如果我将 gun.heft 更改为 guns[gun].heft,我会得到正确的输出。

Behold! Sharpshooter, with overhand heft!
Behold! Pokepistol, with shoulder heft!

似乎我可以在循环中获取枪支的名称,但是我不能对其调用方法来获取重量。为什么?

在 Ruby 中,在一个循环中,索引处的当前项通常是一个对象。不是吗?

最佳答案

But, if I change gun.heft to guns[gun].heft, I get the correct output.

...

It seems that I can get the name of the gun inside the loop, but I can't call a method on it to get the heft. Why?

您的问题中没有尝试对对象使用方法的代码。如果有,它就会起作用,原因与 guns[gun].heft 起作用的原因相同:

// The function we'll make a method
function getGunHeft() {
return this.heft;
}

// Create the objects with that function on them as a method
var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand", getHeft: getGunHeft},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder", getHeft: getGunHeft}
};

// Use the method
function listGuns(guns) {
for ( var gun in guns ) {
console.log("Behold! " + gun + ", with " + guns[gun].getHeft(); + " heft!");
}
}
listGuns(rockSpearguns);

JavaScript 中的“方法”只是附加到对象属性的函数(如上所示直接附加,或通过对象的底层“原型(prototype)”对象附加)。因此,如果您可以访问对象属性,则可以调用它所引用的函数。

当您将函数作为从对象属性获取函数的同一表达式的一部分进行调用时,JavaScript 引擎会在函数调用期间将 this 设置为引用该对象。这就是为什么我在上面使用 this.heft 来访问枪的 heft 属性。

我博客上这篇文章的更多内容:Mythical Methods

关于javascript - 在循环内调用对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com