【发布时间】:2019-02-18 08:57:39
【问题描述】:
我检查了一些有类似问题的问题,但无法处理我有 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 文件并检查控制台,显示以下错误消息:
未捕获的类型错误:无法读取未定义的属性“追加”
如何解决这个问题?
更新:
我遇到的第二个问题(可能是一个单独的问题?)是,如果我写:
function singlyLinkedList() {
this.head = null
}
我收到此错误消息:
未捕获的类型错误:无法设置未定义的属性“头”
【问题讨论】:
-
singlyLinkedList没有返回任何内容。如果你想要一个实例,请使用new。 -
或者,你可以从
singlyLinkedList返回this -
@Tzelon 我尝试了你的想法,但在删除了
if声明并做了:this.head = null然后return this.head但我得到Uncaught TypeError: Cannot set property 'head' of undefined -
我认为你需要像
let linkedList = new singlyLinkedList()一样使用它 -
@CertainPerformance 是对的。您需要使用“新”来获取实例。对不起
标签: javascript function prototype strict