javascript - 使用公共类属性时未定义
问题描述
这真的很奇怪,我不明白为什么会这样。当我调用该startRecording()
方法时,它可以完美运行,我可以测试this.rec
已设置。但是当我调用stopRecording()
方法时,它说那this.rec
是未定义的。如果我知道它已定义,这怎么可能?
问题出在RecorderClass.js
我调用该stopRecording()
方法时。
索引.html
<html>
<body>
<div>
<button id="recordButton">Record</button>
<button id="stopButton">Stop</button>
</div>
<script src="recorder.js"></script>
<script type="module" src="app.js"></script>
</body>
</html>
应用程序.js
import RecorderClass from './RecorderClass.js'
let recordButton = document.getElementById("recordButton")
let stopButton = document.getElementById("stopButton")
let RecorderObject = new RecorderClass()
recordButton.addEventListener("click", RecorderObject.startRecording)
stopButton.addEventListener("click", RecorderObject.stopRecording)
RecorderClass.js
class RecorderClass
{
startRecording()
{
this.AudioContext = window.AudioContext || window.webkitAudioContext
let constraints = { audio: true, video: false }
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
let audioContext = new AudioContext()
this.gumStream = stream
let input = audioContext.createMediaStreamSource(stream)
this.rec = new Recorder(input, { numChannels: 1 })
this.rec.record()
})
// Returns an object !!!!!
setTimeout(() => {
console.log(this.rec)
}, 3000)
}
stopRecording()
{
// Returns undefined !!!!!
console.log(this.rec)
this.rec.stop()
this.gumStream.getAudioTracks()[0].stop()
}
}
export default RecorderClass
这是 CodePen 上的项目(您可以在控制台中看到错误)
解决方案
你在这里失去了this
参考:
recordButton.addEventListener("click", RecorderObject.startRecording)
stopButton.addEventListener("click", RecorderObject.stopRecording)
您将函数引用作为回调传递给addEventListener
. 当事件发生时,将调用该回调而无需任何特定this
绑定。
你应该这样做:
recordButton.addEventListener("click", () => RecorderObject.startRecording())
stopButton.addEventListener("click", () => RecorderObject.stopRecording())
现在在您的对象上调用这些方法,该对象this
在调用期间起作用。
注意:最好用首字母小写字母命名您的实例对象,因为首字母大写通常用于构造函数/类。