i am starting to learn javascript and i got confused on the execution of the properties in the javascript function.
suppose i have a funciton like this
function Counter() {
this.num = 0;
this.timer = console.log('hey');
};
now in this function, i have num and timer as a properties of the function Counter. when i try to make a instance of the function Constructor the timer property gets executed
but when i try to call the timer property explicitly, i am not getting the value / the property is not getting executed.
what is the reason behind it?
now in this function, i have num and timer as a properties of the function Counter.
No, you have num
and timer
properties of objects created by calling Counter
as a constructor (via new
, or Reflect.construct
, etc.).
but when i try to call the timer property explicitly, i am not getting the value / the property is not getting executed
Just briefly on terminology (since this will help as you continue your learning), you don't "call" properties, and properties are not "executed." You "get" their value, or "access" them, or "read" them. (Or, when they're on the left-hand side of an assignment, you "set" them or "assign to" them or "write to" them.)
Your code is successfully getting the value of the timer
property, which is the value that console.log('hey')
returned, which is undefined
.
If you meant for doing something with timer
to make it run the console.log
, you'd want to put it in a function:
this.timer = function() {
console.log('hey');
};
and then call it (because you do "call" functions):
d.timer();
Side note:
If that's what you meant to do, while it's perfectly fine to create functions within the constructor like that, it's slightly more common to assign them to the prototype object that new Counter
will give to the objects it creates. With ES5 and earlier, you'd do that like this:
function Counter() {
this.num = 0;
} // <== No ; here, it's a declaration, not a statement
Counter.prototype.timer = function() {
console.log('hey');
};
In ES2015+, you'd probably use class
syntax instead:
class Counter() {
constructor() {
this.num = 0;
}
timer() {
console.log('hey');
};
}
You use them the same way (via new
).