16/33 Wouldn't this make more sense...?


#1

In this lesson about Methods they create a Method (or what looks to me like a function) called setAge using the "this" keyword inside of it to set the new age of whatever Object calls it. The way they show it looks like this...

var setAge = function (newAge) {
this.age = newAge;
};

var bob = new Object();
bob.age = 30;

bob.setAge = setAge;

bob.setAge(50);

But my questions is this: wouldn't it make more sense to use this "this" keyword in the name/set-up of the function/method itself that way you can skip the step of "bob.setAge = setAge;". The way I see it, the code should look like this...

this.setAge = function (newAge) {
this.age = newAge;
};

var bob = new Object();
bob.age = 30;

bob.setAge(50);

I'm relatively new to this so please let me know if there is a reason that this doesn't work because it seems logical to me.

Thanks!


#2

It won't fly.

this.setAge = function (newAge) {
this.age = newAge;
};

var bob = new Object();
bob.age = 30;

bob.setAge(50);

First off, what is this in,

this.setAge = ...

? Answer: window. We have essentially what we started with:

setAge = ...

When we try to run the method on bob, it will throw an error:

bob.setAge(50);

It will tell us, TypeError: bob.setAge is not a function.

The only way we can have this method work on the object is to make it a property in the same context.

bob.setAge = setAge;

We are assigning a function reference, not a computed return value. If we log out the bob.setAge property, we can see...

console.log(bob.setAge.toString());

we get,

function (newAge) {
    this.age = newAge;
}

#4

I was wondering that as well. Is it allowed in Java and not JS? I vaguely remember being able to do something like this in another language. Also, do you have to make that assignment statement for each object and each method or is there a cleaner way of writing the code in JS? Seems like that could get pretty lengthy and spider-web-ish.


#5

These are, after all, practically rote lessons in mechanics. Definitely it gets more organized, and 'cleaner', as you say.

function Person(name, age){

}
var bob = new Person("Bob", 19);

Evident is that we will be defining at least two properties, name and age. We can instantiate new objects til the cows come home with this function, and some help from the new oeprator.

var mary = new Person("Mary", 23);

Now both of the these objects have Person.prototype in their prototype. Should we decide later to modify that prototype, it would dynamically reflect on all the Person instances.

Person.prototype.setAge = function (newAge){
    this.age = newAge;
};
bob.setAge(20);
mary.setAge(24);
console.log(bob.age, mary.age);     //  20 24

If this isn't 'cleaner', then I don't have a better answer. When we look at the potential, is it any wonder that JS is beating out the horde of languages vying for a niche in the web frontier?