分享

Introduction to Objects I | Codecademy

 LVADDIE 2014-06-16
The "this" Keyword

Our setAge method works great for bob because it updates bob.age, but what if we want to use it for other people?

It turns out we can make a method work for many objects using a new keyword, this. The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used.

// here we define our method using "this", before we even introduce bob

var setAge = function (newAge) {

  this.age = newAge;

};

// now we make bob

var bob = new Object();

bob.age = 30;

// and down here we just use the method we already made

bob.setAge = setAge;

Let's look at the method setAge (line 2) to see how this works. By using the keyword this, setAge will change the age property of any object that calls it. Previously, we had a specific object bob instead of the keyword this. But that limited the use of the method to just bob.

Then when we say bob.setAge = setAge; (line 9), it means whenever we type bob.setAge( ), this.age in the setAge method will refer to bob.age.

Instructions

To show this way of making setAge works just like the one in exercise 2, use bob's setAge method to change his age to 50.

Stuck? Get a hint!

Just like in exercise 2, use bob.setAge(someNewAge); to use the method.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多