如何将创建的对象称为JS中的函数



我有一个类Notify,例如:

class Notify {
    success(text) {
        // TODO
    }
    error(text) {
        // Todo
    }
}
export default new Notify();

当我使用时,我直接致电到此类中的方法(例如Notify.success()(,因此,现在我想尝试一种新的方式来称其为Notify('my title', 'success')。在PHP中,我知道它是__invoke方法,但是在JS中,我不知道如何使用它喜欢它。我可以在class中这样做吗?或者我必须使用"正常"功能。

请帮助我。谢谢。

javaScript中没有__invoke的类似物。您可以制作功能,然后将属性附加到IS,以便它也可以用作对象。

function notifyConstructor() {
  // Make the function
  const notify = (text, type) => {
    switch (type) {
      case 'success': return notify.success(text);
      case 'error': return notify.error(text);
      default: throw TypeError(`Unknown type "${type}"`);
    }
  };
  // Attach public properties and methods to the function
  notify.success = text => {
    // TODO
  };
  notify.error = text => {
    // Todo
  };
  return notify;
}
const notify = notifyConstructor();  // Make a Notify instance
notify('my title', 'success');       // Call the instance
notify.success('my title');          // Call an instance method

您可以使用上下文 this来获取功能。

如果您单独调用函数invoke(stackoverflow错误(。

class Notify {
  constructor() {
  }
  
  invoke(msg, fn) {
    if (this[fn]) {
      this[fn](msg);
    } else throw new Error("Illegal argument Error.");
  }
  
  success(text) {
    console.log('Success:', text);
  }
  error(text) {
    console.log('Error:', text);
  }
}
let notify = new Notify();
notify.invoke('my title', 'success');
notify.invoke('my title', 'error');
notify.invoke('my title', 'ele');

或直接通过实例化对象:

class Notify {
  constructor() {
  }
  
  success(text) {
    console.log('Success:', text);
  }
  error(text) {
    console.log('Error:', text);
  }
}
let notify = new Notify();
notify['success']('my title');
notify['error']('my title');

在JavaScript对象属性中使用DOT(.(是使用数组符号([](访问属性的简短符号。但是,短手表示法确实要求属性名称符合标识符的语法。

假设Notify是导入实例的名称

Notify["success"]("my title"]

等于

Notify.success( "my title")

最新更新