自定义元素在类装饰器上的行为方式不同吗?
示例:
的index.html
<test-2></test-2>
<script src="test2.js"></script>
test2.ts =&gt; 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 :(得分: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;
}
}