How can we set up 'self' with when using 'class'?
I've seen the 'self' variable to get set up for more predictable 'this' usage in javascript classes using the 'function' class declaration. How can we do this with the 'class' declaration?
Function VS Class declarations
// Using the 'function' declaration
function Apple (type) {
var self = this
self.type = type
self.color = "red"
self.getInfo = function() {
return self.color + ' ' + self.type + ' apple'
};
}
// Using the 'class' declaration
class Apple2 {
constructor(type){
var self = this
self.type = type
self.color = "red"
}
getInfo () {
return self.color + ' ' + self.type + ' apple'
}
}
let ap = new Apple('Granny')
let ap2 = new Apple2('Jazz')
console.log(ap.getInfo(), ap2.getInfo())
// prints 'red Granny apple undefined undefined apple'
Edit:
It looks like creating the 'self' variable before the constructor works in the chrome console actually, but webpack is throwing an error for it:
// Using the 'class' declaration
class Apple2 {
self = this
constructor(type){
self.type = type
self.color = "red"
}
getInfo () {
return self.color + ' ' + self.type + ' apple'
}
}
console.log(new Apple2('Jazz').getInfo())