this is not like java.
const team = {
partnerOne: `Team1`,
partnerTwo: `Team2`,
myFunction: function sayTeamNames() {
console.log(`${this.partnerOne} and ${this.partnerTwo}`);
}
}
you need to use this in javascript. Javascript originally was built in a lisp syntax. that's the reason why it has so many functional (as in functional programming) properties.
if you want the access a property you need to define the access of the right memory segment. (Programming languages are usually represented as stack-machines and those stack-machines usually have memory segments). Memory segments basically are just labels that define how to access the memory.
in java and c# the programming languages basically resolves hierarchical over the scopes -> local, param, this ..... so you can write it like
...
myFunction: function sayTeamNames() {
console.log(`${partnerOne} and ${partnerTwo}`);
}
...
because after it looked local
myFunction: function sayTeamNames() {
let partnerOne = 'blub';
let partnerTwo = 'bleh';
console.log(`${partnerOne} and ${partnerTwo}`);
}
it would try to look at the params
myFunction: function sayTeamNames(partnerOne, partnerTwo) {
console.log(`${partnerOne} and ${partnerTwo}`);
}
and than resolve to the virtual-memory-segment to itself 'this'
const team = {
partnerOne: `Team1`,
partnerTwo: `Team2`,
myFunction: function sayTeamNames() {
console.log(`${partnerOne} and ${partnerTwo}`);
}
}
but in js the 'this' segment/pointer/reference is passed via auto currying.
const team = {
....
myFunction: function sayTeamNames() {
console.log(`${partnerOne} and ${partnerTwo}`);
}.bind(this) // this is done magically in the background
...
}
because the original language concept looked more like gnu.org/software/emacs/manual/html_node/elisp/Cal…
But that leads to far. it's just an explanation for the lateron 'funny' difference between
class x {
Z = 'test';
y () {
const subfunction = function(x) {
console.log(this.z); //<- won't work since every function that is created in this way will allways bind 'itself' (in JS every function is an object)
}
}
}
class x {
Z = 'test';
y () {
const subfunction = (x) => {
console.log(this.z); //<- will work since the short function definition always does "autobind" the parent scope (this refers to subfunction which refers to x)
}
}
}
class x {
Z = 'test';
y () {
const subfunction = function(x) {
console.log(this.z); //<- will work since you 'bound' / curried 'this' from the parent context as the own 'this'
}.bind(this);
}
}
There are also JIT differences of behaviour in JS between function and const -> the less 'this' the less complex state the more optimizations can be done automatically.
But this would lead to far.
The main point is. in Javascript, in the current state, you need to write this to access the object context.
At least that's how I understand the language / behaviour. But I have to be honest maybe I overly simplified things.