Noob Concern: Using the JavaScript Function

I am looking through a JavaScript tutorial and I can complete it. But the problem is that I don’t understand what one of the lines does. I have a setAge() function, and then after creating the susan object susan I set one of the properties of this object as the name of the function? I do not understand why this is done. Can't I use a function / method without doing this?

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 age to 35 using the method susan.setAge(35); 
+6
source share
4 answers

Assigning the susan setAge function above

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

which is a function that takes one argument. When susan.setAge(35); is called susan.setAge(35); , this will refer to the caller, susan , updating the age to 35.

Confusion can be used from setAge twice. Susan's function is defined on the left side, the right side is already defined. For instance:

 susan.letMyAgeBe = setAge; susan.letMyAgeBe(35); 

works the same way. setAge also "reused":

 harry = new Object(); harry.iAmThisOld = setAge; harry.iAmThisOld(55); 

Demo http://jsfiddle.net/7JbKY/2/

+8
source

It works due to variable areas.

The first variable setAge is just a function, and you can call it like: setAge(24) This is not so different from function setAge(age) {this.age = age}

After you declare a variable setAge and set it to a function, you can set another variable for this variable. What you do in the object is simple. After you write susan.setAge = setAge; The property of the setAge object will be equal to the previous setAge variable, which is a function. So you can call susan.setAge() .

0
source

let's see what is done in the code -

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

here a function is defined that will change the age of an object variable to that specified when the function is called.

 var susan = new Object(); susan.age = 25; susan.mynewageis = setAge; 

here we set the predefined value susan.age to be changed by the function, and we set the function value of the susan.mynewageis variable to make this function available next time in any other case.

 susan.mynewageis(35); 

here we set susan.age to 35, as indicated by the function call.

I was about to post this answer, but by mistake I hit the submit button and sent an incomplete answer.

0
source

it is a matter of volume and closure. For more information about this, I would recommend you read this article: http://nesj.net/blog/2012/03/javascript-scope-and-closure/

-1
source

Source: https://habr.com/ru/post/917697/


All Articles