简体   繁体   English

在类方法Javascript中引用类变量

[英]Referencing class variable in class method Javascript

I'm defining a class in Javascript meant to serve as an audioplayer compatible with iOS. 我正在用Javascript定义一个类,旨在用作与iOS兼容的音频播放器。 I'm just getting started with the basics, and running into an issue when trying to access a class method. 我刚刚开始学习基础知识,并且在尝试访问类方法时遇到问题。

After creating an instance of the class ( var audio = new WebAudio('soundfile.mp3', document.querySelector(#sound_div) ), and attempting to access the method audio.playSound() , I'm getting: 创建类的实例( var audio = new WebAudio('soundfile.mp3', document.querySelector(#sound_div) ),并尝试访问方法audio.playSound() ,我得到:

ReferenceError: Can't find variable: elem on line 29 ReferenceError:找不到变量:第29行的elem

class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
    }

    context() {
        var AudioContext = window.AudioContext || window.webkitAudioContext;
        var context = new AudioContext();
        return context;
    }

    webAudioTouchUnlock(context) {
       return new Promise(function (resolve, reject) {
       //if AudioContext is suspended, and window has been interacted with
           if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error
           this.elem.addEventListener('touchend', unlock, false);
           } else {
               console.log('context not suspended? Context is ' + context.state);
               resolve(false);
           }
       });
    }

    playSound() {
        this.webAudioTouchUnlock(this.context()).then(function (unlocked) {
            if(unlocked) {
                console.log('playing audio file');
                var audio = new Audio('sound/' + soundFile);
                if (!audio.playing) {
                    audio.play();
                } else {
                    audio.pause();
                }
            }
        }, function(reason) {
            console.error(reason);
        });
        document.body.addEventListener('load', playSound(soundFile));
    }
}

You lose the binding to this when you pass the function to an event listener: 将函数传递给事件侦听器时,您将失去this的绑定:

var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   // this won't point to the instance when called by listener
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error

Arrow functions or manually calling bind(this) can fix it. 箭头函数或手动调用bind(this)可以修复它。 The arrow function will bind this in the function lexically, which means this will be the this value from where it was defined rather than how it is called: 箭头功能将结合this在词法的功能,这意味着this将是this从它被限定,而不是它是如何被调用值:

var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM