I'm trying to understanding how bind()
works. In my JS script, I want to create an instance of a Rectangle class, and then call a function that prints text followed by a property of the rectangle, using the bind()
function. Here's what I have:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
getWidth() {
return this.width;
}
}
let Rectangle1 = new Rectangle(10, 20);
function func1(text) {
console.log(`${text} + ${this.getWidth()}`)
}
let func2 = (text) => {
func1.bind(Rectangle1, text)
}
func2('Rectangle width is: ')
The key is that I want to be able to call a function (func2
) that contains only the beginning text.
Currently this code doesn't print anything.
What am I missing?
SOLUTION:
bind() returns a new function. So func1.bind(Rectangle1, text)
doesn't execute a bound version of func1, it just returns the bound version of func1.
Solution is to change func1.bind(Rectangle1, text)
to func1.bind(Rectangle1)(text)
, which calls the bound version of func1 with text
as input param.
Thanks @Pointy @Bergi and @James for your help.
You want either
const func2 = (text) => {
func1.call(rectangle1, text);
};
or
const func2 = func1.bind(rectangle1);