因此,使用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);


希望不要太困惑,但是如果您中有更多有经验的Java脚本的人可以请您解释我在评论中谈论的所有内容,我将不胜感激。谢谢

最佳答案

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


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

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


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

对于rabbit2rabbit3this分别指向自己。

关于javascript - Javascript帮助:函数/对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39187197/

10-09 21:47