gpt4 book ai didi

javascript - 为什么父自定义元素方法被重写?

转载 作者:行者123 更新时间:2023-12-02 23:32:03 24 4
gpt4 key购买 nike

我创建了一个名为“CursorCell”的自定义元素,它扩展了 HTMLTableCellElement 对象。

我向此自定义元素添加了一个名为“value”的属性。

之后,我创建另一个名为“DateCell”的自定义元素,它扩展了“CursorCell”自定义元素。在“DateCell”中,我想扩展“设置值”方法。

这是我的代码:

class CursorCell extends HTMLTableCellElement {
constructor() {
super();
this.textBox = document.createElement("input");
this.textBox.type = "text";
this.appendChild(this.textBox);
$(this).addClass("cursorCell");
$(this).addClass("borderCell");
}
set textContent(t) {
this.value = t;
}
get textContent() {
return this.textBox.value;
}
set value(v) {
this.textBox.value = v;
}
get value() {
return this.textBox.value;
}
}
customElements.define('cursorcell-string',
CursorCell, {
extends: 'td'
});
class DateCell extends CursorCell {
constructor() {
super();
$(this).addClass("dateCell");
}

set value(v) {
super.value = v;
switch (v) {
case "a":
this.textBox.className = "aShiftColor";
break;
case "b":
this.textBox.className = "bShiftColor";
break;
case "c":
this.textBox.className = "cShiftColor";
break;
}
}

}
customElements.define('datacell-string',
DateCell, {
extends: 'td'
});
$(document).ready(function() {
var t = document.createElement("table");
var row = t.insertRow(t.rows);
var cell1 = new DateCell();
row.id = "bb";
row.appendChild(cell1);
cell1.textContent = "a";

document.body.appendChild(t);
$.each($("tr#bb").children(".cursorCell"),
function(i, val) {
console.log(val.value);
});

});
::selection {
background: none;
/* WebKit/Blink Browsers */
}

::-moz-selection {
background: none;
/* Gecko Browsers */
}

td input[type="text"] {
border: none;
height: 100%;
width: 100%;
text-align: center;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}

td input[type="text"]:focus {
outline: none;
}

table {
border-spacing: 0;
border-collapse: collapse;
}

.aShiftColor {
background-color: #ff99cc;
}

.borderCell {
border: 1px solid #e0e0e0;
}

.bShiftColor {
background-color: #ffffcc;
}

.cursorCell {
margin: 0px;
width: 25px;
padding: 0px;
text-align: center;
font-size: 17px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

扩展“set value”方法后,“set value”方法工作正常,但无法从“DateCell.value”读取值。

当我从“DateCell”中删除“set value”方法时,我可以从“DateCell.value”中读取值。

那么,为什么 CursorCell“获取值”方法被重写?

最佳答案

value 是一个属性。对于属性,setter 和 getter 是一起工作的。

您不会重写 setter 或 getter,而是重写属性本身。

如果您使用 setter(set value)覆盖它,则需要同时使用 getter(get value)覆盖它。否则 JS 引擎会认为 getter 是未定义

您还应该在类扩展中定义 getter:

class DateCell extends CursorCell {    
//...
set value(v) { super.value = v }
get value() { return super.value }
}

关于javascript - 为什么父自定义元素方法被重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com