使用新的类属性初始化器,您可能根本不需要函数(对于简单的表达式)。
初始化器是类定义上下文中的=表达式,它就像是构造器中的表达式,所以定义了this(因为初始化器在构造器链之后)。
class Toto {
foo = 'bar'
bar = this.foo
baz = this.method()
method(){ return 'baz' }
}
console.log( new Toto )
//> Toto {foo: "bar", bar: "bar", baz: "baz"}
静态初始化器的工作方式相同,但this 是实际的构造函数(类),与在静态方法中定义的方式相同。
class Toto {
static foo = 'bar'
static bar = this.foo
static baz = this.method()
static method(){ return 'baz' }
}
console.dir( Toto )
//> class Toto {name: "Toto", foo: "bar", bar: "bar", baz: "baz", method: ƒ method()}
使用父类声明初始化时调用的静态方法非常方便:
class Base extends HTMLElement {
static define( tag )
{
return customElements.define( this, tag )
}
}
//then
class MyElement extends Base {
constructor(){ ... }
static defined = this.define( 'my-el' )
}
您也可以使用静态 getter/setter:
/** utils */
const CSS = css=> { let s = new CSSStyleSheet; s.replaceSync(css); return s }
class Base extends HTMLElement {
/**
* node.shadowRoot getter to access shadowRoot with direct creation if not existing yet.
* @exemple class extends HTMLElement { constructor(){ super(); this.shadowRoot.innerHTML = '...' } }
* @exemple class extends HTMLElement { html = this.shadowRoot.innerHTML = '...' }
*/
get shadowRoot()
{
return super.shadowRoot || this.attachShadow({mode:'open'})
}
adoptedCSS = this.shadowRoot.adoptedStyleSheets = [ this.constructor.css ]
static set tag( v )
{
return customElements.define( this, v )
}
}
//then
class MyElement extends Base {
title = 'Default title'
html = this.shadowRoot.innerHTML = `
<div class=super>
<h1>${this.title}</h1>
</div>
`
$title = this.shadowRoot.querySelector('div > h1')
static css = CSS`
:host { outline: 1px solid blue }
div { outline: 1px solid green }
`
static defined = this.tag = 'my-el'
// static tag = 'my-el' << this won't work because initializers use
// Object.defineProperty and not a direct set, so the setter
// will be overwritten!
}
// Note: no need of any framework here
支持:
来源: