【问题标题】:How to access the object that used Decorator?如何访问使用装饰器的对象?
【发布时间】:2018-10-24 05:05:59
【问题描述】:

我想通过使用装饰器注入一些需要许多组件的 HTML 元素。这是我要实现的用法:

const serializedCSS = '...';    // Serialized CSS

@injectStyle(serializedCSS);
class MyComponent extends HTMLElement {
   ...

我想将序列化的 css 发送到装饰器,但是我找不到如何访问“MyComponent”类,我必须访问它自己的属性来创建新的样式元素并附加为子元素。

function injectStyle(target: any) {
    console.log(target);

    // ??? HOW TO ACCESS THE OBJECT? ///

    function f(...args:any) {

    }

    return f;
}

我找不到任何相关的解决方案。任何建议都会非常感激!

【问题讨论】:

  • 你的意思是要访问调用new MyComponent时创建的对象?
  • @mins 我想访问与 new 关键字一起使用后的对象,以访问内部属性。

标签: javascript decorator


【解决方案1】:

这是我的解决方案。

export function injectStyle(css:string, ...args:any) {
    return function(target:any) {
        // Now I can access target object with "target"!
        target.doSomething ... 
        ...
    };
}

现在我可以像这样使用 injectStyle 装饰器:

@injectStyle(require('./style.css'))
class App extends HTMLElement {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2018-09-08
    • 1970-01-01
    • 2017-08-15
    • 2010-12-24
    • 2011-06-25
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多