【问题标题】: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}

    【讨论】:

    • 那么接口有点像面向对象编程中的类?
    • 在这种情况下是的。好比喻
    • 如果有帮助,请随时接受这个答案
    猜你喜欢
    • 2016-10-07
    • 2011-03-02
    • 2016-11-28
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多