Quick question (my code works)


#1


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


The code works, I just don't know why we use a named method inside the constructor. I tried to create an instance of this method without relying on the 'this' keyword and I always get stuff on simple little inquiries like this, but I just wanted to know if you have to use a named method for this to work because it doesn't explain why we name the function here. Before we made functions anonymous, why wouldn't code academy elaborate this here?


function Person(job, married) {
    this.job = job;
    this.married = married;
    // add a "speak" method to Person!
    //make this method work without the 'this' keyword. Do you have to create an anonymous function? 
    this.speak = function(){
       console.log("Hello!");
    }
}

var user = new Person("Codecademy Student",false);
//instead of going user.speak, just calling the function with, "speak();"
user.speak();


#2

Javascript doesn't have classes, it uses prototypes instead. The prototype is checked when a name isn't found in an object.

So you can either create the method for each object so that each object has its own method, or put the method in the prototype with the effect that all objects of that constructor will refer to the same method.

Also, that is an anonymous function, look at how it was created:

function() {
    console.log("Hello!");
}

No name, see?


#3

I keep forgetting that an anonymous function is declared in a variable and a named function isn't.


#4

A function statement creates a variable as well. The biggest difference is that one is an expression and the other is a statement. And.. it gets a name attribute. Function statements are also executed before the rest of the code runs, as opposed to when execution reaches the line where it's defined.

There are also named function expressions, I might still consider that anonymous though, since it's an expression.

..And there's a function constructor.

console.log(new Function('name', 'return \'Hello \' + name')('bob'));

#5

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