You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中bind()绑定类实例调用函数无输出?问题分析与解决

关于JavaScript中bind()方法的使用问题

我正在尝试理解bind()的工作原理。在我的JS脚本中,我想要创建一个Rectangle类的实例,然后调用一个函数,使用bind()函数打印自定义文本以及该矩形的属性。我的代码如下:

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: ')

核心需求是我希望调用仅传入起始文本的func2函数。但目前这段代码没有任何输出,请问我遗漏了什么?


解决方案

bind()会返回一个新函数。因此func1.bind(Rectangle1, text)并不会执行绑定后的func1,只是返回绑定版本的func1。

解决方法是将func1.bind(Rectangle1, text)修改为func1.bind(Rectangle1)(text),这样就会以text为输入参数调用绑定后的func1。

感谢@Pointy、@Bergi和@James的帮助。


内容的提问来源于stack exchange,提问作者gkeenley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:57:15