8.4 Can I See Your References?


#1


https://www.codecademy.com/en/courses/objects-ii/0/4?curriculum_id=506324b3a7dffd00020bf661


For the method, I can't just put in this;

sayJob: function() {
// complete this method
console.log("Hi, I work as a " + job);

because job is not a variable, right? So it's not defined. I'm questioning it because I know properties are sort of like variables associated with an object and if I'm creating the method within the object, I was thinking I might just be able to use the property. But I can't. And I'm assuming it's because job is not defined as a var. Is that correct?


var james = {
    job: "programmer",
    married: false,
    sayJob: function() {
        // complete this method
        console.log("Hi, I work as a " + this.job);
    }
};

// james' first job
james.sayJob();

// change james' job to "super programmer" here
james.job = "super programmer"

// james' second job
james.sayJob();


#2

Hey kevin, it seems like the lessons (whatever they're teaching) are getting to you. Try taking a break?

What you have In your example is a literal notation, which just means that you're building & initializing your object right away, assigning it's properties and methods directly to the identifier.

Your object is now ready for use, including your method & properties, and your method self-references the object using the this keyword. This method (which is just a property containing a function) is simulating a getter, a method type that retrieves a value, often from elsewhere within the object.

MDN offers a good explanation.

MDN Getter Syntax
The get syntax binds an object property to a function that will be called when that property is looked up.

So instead of having to write your function out as object.sayJob() you can simply write the property name object.sayJob.

The conventional format for writing getter methods is as such

var object = {
    Job: "Person",
    get sayJob: function() {
       return this.Job;
    }
}

However with the newest release of JS you can now write regular functions into an object, without placing them in properties, nor having to declare them as getters or setters.

var object = {
    Job: "Person",
    sayJob() {
       return this.Job;
    }
}

The purpose of understanding this is that either way you write a method, your functions inside objects retrieve the data dynamically; whether you've just initialized your object, or you change a properties value later on, the function behaves the same.


"this" keyword Doubt in JAVASCRIPT
#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.