im trying to make a function work inside the main timeline of adobe animate canvas. I have that code:
function player(){
var power = 19;
}
console.log(this.power);
When i execute it , it says undefined.Can anyone explain me why?
Inside your method player() your define a local variable power which only exist inside the scope of that function, elsewhere there is no such variable. So when you write you are actually referring to the global variable window.power (this is the window in this case) is not defined.
A final note when you correct this you still need to execute the function.
You can either define power globally or run the console.log inside your function where that variable is defined:
First case:
var power;
function player() {
power = 19;
}
player();
console.log(power);
Second case:
function player(){
var power = 19;
console.log(power);
}
player();
Note: Whenever you try to access a variable outside the scope of any functions it's accessing that window object as: window.someVariable so in this case you can just do someVariable as in the two examples above.
The 'this' keyword refers to which object is calling a function, not the actual function itself.
For example:
let player = { func: function() { console.log(this.power); }, power: 10 }
player.func();
//will log 10 because you invoked the function from the player object, and there is a property player.power and it equals 10.
//For contrast: now make a variable in the global scope and store the same function to the new variable:
let sameFunction = player.func;
//under the hood, the code above will be:
window.sameFunction = player.function or window.sameFunction = func: function() { console.log(this.power);}
sameFunction();
will log undefined because sameFunction is pointing to the function stored at player.func BUT you are invoking it from the global object, and that object does not have a property named power.
invoking sameFunction() is the same as invoking window.sameFunction() when window is the global object. Your window object does not have a property named power; so this.power is undefined.
(When you see the 'this' word used inside of function declarations, it is possibly a constructor function. These functions are structured in order to create objects. To use them, you have to understand the new keyword and what it does).