const transformer = {
fraction: 'Autobots',
hasOwnProperty() {
return 'Decepticons!';
},
};
// output: 'Decepticons'
console.log(transformer.hasOwnProperty('fraction'));
// output: true
console.log(Object.hasOwn(transformer, 'hasOwnProperty'));
August 5th, 2022
A safe way to check if an object has a specific property, is to use Object.hasOwn
. It is possible to do the same with Object.prototype.hasOwnProperty
, but the problem is, that the object could have it's own proerty named hasOwnProperty
.
const decepticons = ['Megatron', 'Starscream', 'Blitzwing'];
const lastDecepticon = decepticons.at(-1);
console.log(lastDecepticon); // output: 'Blitzwing'
August 4th, 2022
To get the last item of an array, we had to write array[array.length-1]
. A shorter way is to use the at()
method.
class Transformer {
#transform() {
console.log('Fancy sound! 🎶');
}
canTransform() {
return #transform in this;
}
}
const optimusPrime = new Transformer();
console.log(optimusPrime.canTransform()); // true
August 3rd, 2022
We can use the in
operator to check if an object
has a given private property.
class transformer {
name: 'Optimus Prime';
#previousName: 'Orion Pax'; // private attribute
rollOut() {
//...
}
// private method
#transform() {
//...
}
}
August 2nd, 2022
Until now, the convention was to use the _
for private attributes and methods. However, this had not been able to prevent the abuse.
To declare a private attribute or method, just put a #
in front of it.
class Autobot {
name = 'Optimus Prime';
fraction = 'Autobots';
}
const transformer = new Autobot();
// output: I am Optimus Prime and leader of the Autobots!
console.log(`I am ${transformer.name} and leader of the ${transformer.fraction}!`);
August 1st, 2022
In object-oriented programming, class attributes are often declared in the constructors. In JS, no constructor is needed.