Quick question (my code works)



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(){

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


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() {

No name, see?


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


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'));


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