2017-03-25 96 views
0

自定义元素对类装饰器的作用不同?自定义元素和类装饰器

实施例:

的index.html

<test-2></test-2> 
<script src="test2.js"></script> 

test2.ts => test2.js(目标:es2017)

function defineClass(tagname: string) { 
    return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { 
    console.log("Define: " + constructor.name) 
    window.customElements.define(tagname, constructor) 
    return class extends constructor { 
     newProperty = "decorator"; 
     hello = "decorator"; 
    } 
    } 
} 

@defineClass('test-2') 
class Greeter2 extends HTMLElement{ 
    property = 'property2' 
    hello = 'hello2' 
    constructor() { 
    super() 
    console.log(this.hello) 
    } 
    connectedCallback() { } 
    disconnectedCallback() { } 
    attributeChangedCallback(name: string, oldValue: string, newValue: string) { } 
    adoptedCallback() { } 
} 
console.log('test-2: ', document.querySelector('test-2').hello) 

@defineClass('test-3') 
class Greeter3 { 
    property = 'property3' 
    hello = 'hello3' 
    constructor() { 
    console.log(this.hello) 
    } 
} 
console.log('test-3: ', new Greeter3()); 

输出:

Define: Greeter2 
hello2 
test-2: hello2 <= expected "decorator" like Greeter3 does 

Define: Greeter3 
hello3 
test-3: Object {property: "property3", hello: "decorator", newProperty: "decorator"} 

是这是假设正在工作的方式?如果是这样,为什

回答

0

为了找到解决方案,请拨打https://github.com/rictic,询问他是否有时间在堆栈上回答它,但不认为他有帐户,因此我将其粘贴。

function defineClass(tagname: string) { 
    return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { 
    console.log("Define: " + constructor.name) 
    const generated = class extends constructor { 
     newProperty = "decorator"; 
     hello = "decorator"; 
    } 
    window.customElements.define(tagname, generated) 
    return generated; 
    } 
}