我创建了一个名为"CursorCell"的自定义元素,它扩展了HTMLTableCellElement对象。
我向此自定义元素添加了一个名为"value"的属性。
之后,我创建了另一个名为"DateCell"的自定义元素,它扩展了"CursorCell"自定义元素。在"日期单元格"中,我想扩展"设置值"方法。
这是我的代码:
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>
扩展"设置值"方法后,"设置值">方法正常工作,而我无法从"日期单元格.值"中读取值。
当我从"DateCell"中删除"set value"方法时,我可以从"DateCell.value"中读取值。
那么,为什么CursorCell"get value"方法被覆盖呢?
value
是一个属性。对于一个属性,二传手和吸气手一起工作。
您不会覆盖资源库或 getter,而是覆盖属性本身。
如果你用二传手(set value
(覆盖它,你需要同时用一个getter(get value
(覆盖它。否则JS引擎会认为吸气剂是undefined
。
您还应该在类扩展中定义 getter:
class DateCell extends CursorCell {
//...
set value(v) { super.value = v }
get value() { return super.value }
}