guys:
I am new to javascript. I have a question about the keyword this. I had expected both draws1 and drawc1 show window in the browser’s developer tool. but calling draws1 only returns undfined. I wonder why different declartion way cuses the difference. This is my code:
class Square {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
}
//instance method
move () {
console.log('move this circle with radius of ', this.size, ' to the position x = ', this.x, ' y = ', this.y);
}
draw() {
console.log(this);
}
}
const Circle = function(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
//instance method
this.move = function() {
console.log('move this circle with radius of ', this.radius, ' to the position x = ', this.x, ' y = ', this.y);
}
this.draw = function () {
console.log(this)
}
}
console.log('#########Square');
const s0 = new Square(0, 0, 10);
s0.draw();
const draws1 = s0.draw;
console.log(draws1);
draws1();
console.log('#########Circle');
const c0 = new Circle(0, 0, 10);
c0.draw();
const drawc1 = c0.draw;
console.log(drawc1);
drawc1();