无法扩展此JavaScript对象

时间:2019-02-18 08:57:40

标签: javascript function prototype strict

我检查了类似问题的一个问题,但无法解决我的 file.js 问题:

'use strict'

function singlyLinkedList() {
  if (this ) {
    this.head = null
  }
}

singlyLinkedList.prototype.append = function(value) {
  let node = {
    data: value,
    next: null
  }
  if( !this.head ) {
    this.head = node
  } else {
    let pointer = this.head
    while( pointer ) {
      pointer = pointer.next
    }
    pointer.next = node
  }
}

我从 index.html 打来的电话:

<!DOCTYPE html>
<html>
  <head>
    <title> Test </title>
    <meta charset="UTF-8">
    <script src="file.js"></script>
  </head>
  <body>
    <script>
      let linkedList = singlyLinkedList()
      let integersArray = [1, 22, 333, 4444]
      integersArray.forEach(element => linkedList.append(element))

    </script>
  </body>
</html>

使用Chrome浏览器浏览此HTML文件并检查控制台,会显示以下错误消息:

  

未捕获的TypeError:无法读取未定义的属性“ append”

该如何解决?

更新

我对此有第二个问题(也许是一个单独的问题?),如果我写:

function singlyLinkedList() {
    this.head = null
}

我收到此错误消息:

  

未捕获的TypeError:无法设置未定义的属性“ head”

1 个答案:

答案 0 :(得分:1)

您需要照顾的几件事

  1. 使用new关键字创建“ singlyLinkedList”的实例
  2. 您的while循环终止条件不正确。应该是while( pointer.next )

检查以下版本,

//create a `file.js` file and put this code inside that. running this code snippet on stackoverflow util wont work as you need a separate `file.js`

'use strict';

function singlyLinkedList() {
    this.head = null;
}

singlyLinkedList.prototype.append = function(value) {
    let node = {
        data: value,
        next: null
    };
    if( !this.head ) {
        this.head = node
    } else {
        let pointer = this.head;
        while( pointer.next ) {  //check this
            pointer = pointer.next
        }
        pointer.next = node
    }
};
<!DOCTYPE html>
<html>
  <head>
    <title> Test </title>
    <meta charset="UTF-8">
    <script src="file.js"></script>
  </head>
  <body>
    <script>
        let linkedList = new singlyLinkedList(); // check this
        let integersArray = [1, 22, 333, 4444];
        integersArray.forEach(element => linkedList.append(element));
        console.log('linkedList: ', linkedList);

    </script>
  </body>
</html>

enter image description here

enter image description here

它将记录类似的内容,

enter image description here

我坚信,要使用new概念的好处,您需要使用singlyLinkedList关键字来创建prototype函数的实例