【问题标题】:Understanding the difference between interface and objects in DOM理解DOM中接口和对象的区别
【发布时间】:2021-06-30 09:30:23
【问题描述】:
在文档对象模型的上下文中,接口和对象有什么区别?
这是我目前的理解。如果我错了,请纠正我。
接口:-接口仅定义 DOM 中的不同部分。他们有什么属性,他们有什么方法,等等。接口是使用接口定义语言定义的。
对象:-对象用于实现接口指定的那些规范。
注意:- 我是 javascript 的初学者,并试图了解接口与 DOM 和 Javascript 的关系
【问题讨论】:
标签:
javascript
object
dom
interface
【解决方案1】:
一个很好的例子是HTMLTableElement 接口
当你使用时:
const myTable = document.createElement('table');
浏览器从标签名称中知道要使用哪个接口,并返回一个带有该接口属性和方法的对象。
现在我们可以这样做了:
const row = myTable.createRow()
这是一个由HTMLTableElement接口定义的方法,使用HTMLTableRowElement接口创建插入到表中的新行对象。
用javascript结合起来,完整的建一个表:
const myTable = document.createElement('table');
// set some property values on the object
myTable.border = 1;
// add a <caption>
const cap = myTable.createCaption();
cap.textContent = 'My Cool Table'
// create some rows
for(let i = 0; i < 3; i++){
const row = myTable.insertRow()
// use inertCells() defined in HTMLTableRowElement interface
for( let j=0; j < 3; j++){
// new cell object has been inserted
const cell = row.insertCell();
// set properties of the cell object
cell.textContent = `${i+1}:${j+1}`
}
}
// finally insert the whole table object into the dom
document.body.append(myTable)
// Read some properties of the table object
//like how many rows in table
console.log('# of rows in myTable =', myTable.rows.length)
// what's the caption text
console.log('Caption says: ', myTable.caption.textContent)
td{ width: 30px}