如何使用' this '像一个对象,并通过字符串获得它的变量/函数

How to use `this` like an object and get its variables/functions by a string?

本文关键字:函数 字符串 变量 this 何使用 一个对象      更新时间:2023-09-26

我有一个对象

function Obj()
{
}
Obj.prototype.doSomething = function(thing)
{
    this["do" + thing]();
}
Obj.prototype.doAlert = function()
{
    alert("Alert!");
}
var obj = new Obj();
obj.doSomething("Alert");

这只是我的对象的简化版本,而且要大得多。

我想做的是,如果你传入'Alert',它将运行this.doAlert();,如果我传入'Homework',它将运行this.doHomework();

显然,在这种情况下,这样做是愚蠢的,但我的最终项目将完全不同。

它可以很好地与window:

window["do" + thing]();

但我不希望它是一个全局函数,但要成为obj的一部分。

有人知道我会怎么做吗?

提前感谢!

事实证明,当您通过this['functionName']获得函数时,this不会绑定到它。

这意味着你不能在任何函数中使用this.foo

为了解决这个问题,我使用了以下代码:
this["do" + thing].bind(this)();

代替this["do" + thing]();

JSFiddle: https://jsfiddle.net/auk1f8ua/