You need to enable JavaScript to run this app. 如何将类的方法作为参数传入函数以实现无限循环?
优惠活动
大模型
产品
解决方案
定价
更多

如何将类的方法作为参数传入函数以实现无限循环?

实现类方法的无限循环调用

你的代码目前有两个问题:一是传递方法时丢失了this上下文,导致调用时无法访问MyProperty;二是虽然逻辑上有调用链,但因为this绑定错误会先报错,没法进入循环。要实现无限循环,得先修复this绑定问题,再确保调用链能持续触发。

解决方法1:用bind绑定上下文

修改MyMethod里传递方法的方式,用bind(this)把当前实例的上下文绑定到方法上,这样每次调用时this都指向类实例:

class MyClass {
    MyProperty;
    constructor() {
        this.MyProperty = "Some value";
    }
    MyMethod() {
        console.log(this.MyProperty);
        // 绑定this后再传递方法
        MyFunction(this.MyMethod.bind(this));
    }
}

function MyFunction(MyParameter){
    MyParameter();
}

let Test = new MyClass()
Test.MyMethod()

解决方法2:用箭头函数包裹

箭头函数会继承当前作用域的this,用它包裹方法调用,也能保证上下文正确:

class MyClass {
    MyProperty;
    constructor() {
        this.MyProperty = "Some value";
    }
    MyMethod() {
        console.log(this.MyProperty);
        // 用箭头函数传递带上下文的方法调用
        MyFunction(() => this.MyMethod());
    }
}

function MyFunction(MyParameter){
    MyParameter();
}

let Test = new MyClass()
Test.MyMethod()

原理说明

两种方法都是为了保证MyMethod被调用时,this始终指向MyClass的实例,避免访问MyProperty时报错。同时,每次调用MyMethod都会触发MyFunction,而MyFunction又会再次调用MyMethod,形成无限递归循环,持续打印MyProperty的值。

内容的提问来源于stack exchange,提问作者Oscar Humberto Garcia Russi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:31:02