无法扩展此JavaScript对象

问题描述 投票:0回答:1

我检查了一些类似问题的问题但无法应对我的文件.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:无法读取undefined的属性'append'

如何解决这个问题?

更新:

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

function singlyLinkedList() {
    this.head = null
}

我收到此错误消息:

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

javascript function prototype strict
1个回答
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概念的好处

© www.soinside.com 2019 - 2024. All rights reserved.