'JavaScript assigning function to object property
I'm going through a JavaScript tutorial and I'm able to complete it. But the problem is that I don't understand what one of the lines is doing.
I have a function setAge()
and then later after creating a susan
object I set one of the properties to that object as the name of the function? I don't understand why this is done. Wouldn't I be able to use the function/method without doing this?
The tutorial code:
var setAge = function (newAge) {
this.age = newAge;
};
var susan = new Object();
susan.age = 25;
susan.setAge = setAge; //how the hell does this work?
// here, update Susan's age to 35 using the method
susan.setAge(35);
Solution 1:[1]
It's assigning susan
's property setAge
to the function defined above,
function (newAge) {
this.age = newAge;
};
which is a function accepting one argument. When susan.setAge(35);
is called, this
will refer to the caller, susan
, updating her age to 35.
The confusion might be from setAge
being used twice. Susan's function gets defined on the left side, the right side is already defined. For example:
susan.letMyAgeBe = setAge;
susan.letMyAgeBe(35);
works the same. setAge
is also "reusable":
harry = new Object();
harry.iAmThisOld = setAge;
harry.iAmThisOld(55);
Solution 2:[2]
It works because of variable scopes.
The first setAge
variable is just a function and you can call it like: setAge(24)
It's not so much different than function setAge(age) {this.age = age}
After you declare the setAge variable and set it's content to a function, you can set another variable to this variable. What you are doing in the object is just this. After you write susan.setAge = setAge;
Your object's setAge property will be equal to the previous setAge variable which is a function. So, you can call susan.setAge()
.
Solution 3:[3]
let's see what is done in the code-
var setAge = function (newAge) {
this.age = newAge;
};
here a function is defined which will change the variable age of a object to the one specified while calling the function.
var susan = new Object();
susan.age = 25;
susan.mynewageis = setAge;
here we are setting a predefined value to susan.age which will be changed by the function and we are setting the value of the function to variable susan.mynewageis to make the function available next time in any other case.
susan.mynewageis(35);
here we are setting the value of susan.age to 35 as specified when calling the the function.
I was going to post this answer but by mistake i pressed submit button and posted incomplete answer.
Solution 4:[4]
this is a matter of scope and closure. For more info around this I'd recommend you read this article: http://nesj.net/blog/2012/03/javascript-scope-and-closure/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | cnkt |
Solution 3 | NewUser |
Solution 4 | JaggenSWE |