gpt4 book ai didi

Javascript 帮助 : Functions/Objects

转载 作者:行者123 更新时间:2023-11-30 00:04:02 28 4
gpt4 key购买 nike

因此,使用 Code Academy,我在 Javascript 教程的“对象”部分,我真的很难全神贯注于函数和对象。我想要一些帮助并用下面的部分代码进行解释。我在每一行上都评论了我需要帮助的内容。非常感谢。

// Obviously declaring the Rabbit function with adjective to be called

function Rabbit(adjective) {

// I don't understand this line, or the context of why this is being used.

this.adjective = adjective;

// Why declare another function here? Is a function within a function
// considered a Method or is that only Function within an Object?

this.describeMyself = function() {

// I get this part but why does it need a function to do this?

console.log("I am a " + this.adjective + " rabbit");
};
}

// I don't get this either, Isn't this declaring a new object? How can
// that be when you only have a Function named Rabbit?

var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

// How could this work if describeMyself is in the Rabbit function and
// has nothing to do with rabit1?

console.log(rabbit1.describeMyself);
console.log(rabbit2.describeMyself);
console.log(rabbit3.describeMyself);

希望不要太困惑,但如果你们中任何更有经验的 Javascript 人可以友好地解释我在评论中谈到的一切,我将不胜感激。谢谢

最佳答案

  1. Rabbit 是一个构造函数,当使用 new 关键字调用时,它会生成一个实例
  2. 当您这样做时,this 指向您创建的实例

因此,通过 var rabbit1 = new Rabbit('fluffy'),您创建了一个看起来像这样的对象并将其分配给变量 rabbit1:

{
adjective: 'fluffy',
describeMyself: function() {...}
}

由于 rabbit1.describeMyself 中的 this 指向实例本身 (rabbit1),当您调用 rabbit1.describeMyself() this.adjective 实际上给你 rabbit1.adjective。这就是为什么您会得到 'fluffy' 的原因。

对于rabbit2rabbit3this分别指向它们自己。

关于Javascript 帮助 : Functions/Objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187197/

28 4 0
文章推荐: javascript - 使用登录保护 wordpress 自定义页面
文章推荐: android - 使用 putExtra 传递 ArrayList 数据