This question already has answers here:
Javascript: Do I need to put this.var for every variable in an object?
(6 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 9 days ago.
I have the following class:
class Voice{
constructor(){
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = new SpeechRecognition(); //criou uma instance
recognition.onstart = () => { //inicia quando aperta espaço
//console.log("starting listening, speak in microphone");
}
recognition.onspeechend = () => { //inicia quando para de ouvir pessoa falando
//console.log("stopped listening");
recognition.stop();
}
recognition.onresult = (result) => { //mostra no console o resultado da frase falada atraves de uma arrow function
var word = result.results[0][0].transcript;
console.log(word);
}
recognition.start();
}
}
export {Voice};
So, I would like to instantiate the class Voice in the main class and access the variable "word".
In the main class, I've tried:
function keyDown(e){
if (e.code=='Space'){
let myWord = new Voice();
console.log(myWord.word);
}
}
function keyDown(e){
if (e.code=='Space'){
//voice();
let myWord = new Voice();
console.log(`${myWord.word}`);
}
}
For both attempts, I got "undefined" as a result.
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 10 months ago.
I have the following code in my ngOnInit:
ngOnInit(): void {
let selectedArea:any = null;
let areas = document.querySelectorAll<SVGElement>('path'); // gets an array of all of the paths in the DOM
areas.forEach((area) => { // for each svg path
area.addEventListener('mouseover', function () {
area.style.fill = '#2100b6'; // add hover
});
area.addEventListener('mouseout', function () {
area.style.fill = ''; // return to default on mouse out
});
area.addEventListener('click', function () {
if (selectedArea) {
area.style.fill="black";
}
if (selectedArea !== area.id) {
selectedArea = area.id;
area.setAttribute('class', 'selectedArea'); // changed
area.style.fill="black";
}
console.log(selectedArea);
});
this.selectedRegion = selectedArea
});
}
selectedRegion : number = 0
"selectedArea" logs the selected region's code from an SVG map.
I tried to get that into the new variable "selectedRegion", but it did not work.
So, I want to use "selectedArea" outside of ngOninit, but I don't have any idea, how to do it.
This question already has answers here:
"this" keyword in event methods when using JavaScript prototype object
(4 answers)
Closed 2 years ago.
I'm wanting to access this from within an addEventListener.
With my example below I want to output this.settings.car when a div is clicked.
I could write var that = this within the this.init = function() { //here } and access it using that.settings.car, however if I run multiple instances of this code then that will always reference the last instance.
Else I could rewrite the addEventListener to be:
this.settings.wrap.addEventListener('click', function (e) => {
console.log(this.settings.car)
})
and that'll work, however this will lead to me writing lots of duplicate code instead of 1 function.
I've been scratching my head at this for a while now. How can I access this from within the this.test function?
var gauge = (function() {
return function() {
this.settings = {
car: undefined,
}
this.init = function(e) {
this.settings.wrap = document.querySelector(e.wrapper)
this.settings.car = this.settings.wrap.innerText
this.settings.wrap.addEventListener('click', this.test)
}
this.test = function(e) {
console.log('clicked')
console.log(this.settings.car)
}
}
}())
// init
let boy = new gauge()
boy.init({
wrapper: '.boy'
})
let girl = new gauge()
girl.init({
wrapper: '.girl'
})
div {display:block;background:grey;margin:20px;height:200px;width:200px;color:white;text-align:center;line-height:200px;}
<div class="boy">ford</div>
<div class="girl">ferrari</div>
Here's a jsbin of the issue: https://jsbin.com/xayuheyime/1/edit?html,js,console,output
You need to use Function.prototype.bind to set the this value.
this.settings.wrap.addEventListener('click', this.test.bind(this))
var gauge = (function() {
return function() {
this.settings = {
car: undefined,
}
this.init = function(e) {
this.settings.wrap = document.querySelector(e.wrapper)
this.settings.car = this.settings.wrap.innerText
this.settings.wrap.addEventListener('click', this.test.bind(this))
}
this.test = function(e) {
console.log('clicked')
console.log(this.settings.car)
}
}
}())
// init
let boy = new gauge()
boy.init({
wrapper: '.boy'
})
let girl = new gauge()
girl.init({
wrapper: '.girl'
})
div.boy, div.girl {display:block;background:grey;margin:20px;height:200px;width:200px;color:white;text-align:center;line-height:200px;}
<div class="boy">ford</div>
<div class="girl">ferrari</div>
Arrow function seems fine here. Another way is how you suggested, use var that = this before your this.init function, and use that on your event handler call.
var gauge = (function() {
return function() {
this.settings = {
car: undefined,
}
this.init = (e) => {
this.settings.wrap = document.querySelector(e.wrapper)
this.settings.car = this.settings.wrap.innerText
this.settings.wrap.addEventListener('click', this.test)
}
this.test = () => {
console.log('clicked')
console.log(this.settings.car)
}
}
}())
// init
let boy = new gauge()
boy.init({
wrapper: '.boy'
})
let girl = new gauge()
girl.init({
wrapper: '.girl'
})
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
class TestClass {
constructor(word) {
this.word = word;
window.addEventListener("keypress", this.logCharCodeAndWord);
window.addEventListener("click", this.logWord)
}
logCharCodeAndWord(e) {
console.log(e.charCode);
console.log(this.word)
}
logWord() {
console.log(this.word)
}
}
var testObject = new TestClass("banana");
I don't even know how to ask this question, but here's my problem...
console.log(this.word)
This logs "undefined" to the console, because this refers to window instead of the TestClass. I want this.word to refer to "banana", and I would like to be able to use the e.charCode part at the same time.
How would I do that?
You need to either pass in the this of your class object:
window.addEventListener("click", this.logWord.bind(this))
Or you can use an arrow-function:
window.addEventListener("click", () => this.logWord())
Simply pass this to your event listeners.
window.addEventListener("keypress", e => this.logCharCodeAndWord(e, this));
window.addEventListener("click", () => this.logWord(this));
class TestClass {
constructor(word) {
this.word = word;
window.addEventListener("keypress", e => this.logCharCodeAndWord(e, this));
window.addEventListener("click", () => this.logWord(this));
}
logCharCodeAndWord(e, self) {
console.log(e.charCode);
console.log(self.word)
}
logWord(self) {
console.log(self.word)
}
}
var testObject = new TestClass("banana");
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have code like this:
class Korisnik
{
constructor(korisnikId)
{
this.KORISNIKID = korisnikId;
this.IME = "";
this.UNIQUE_KEY = "";
this.Initialize();
}
Initialize(kid)
{
$.ajax({
type: "POST",
url: "../Php/Korisnik_Get.php",
data: {"korisnikId" : this.KORISNIKID},
success: function(result)
{
var arr = result.split('|');
this.IME = arr[0];
this.UNIQUE_KEY = arr[1];
}
});
}
get naziv()
{
alert("IME: " + this.IME); //Undefined
return this.IME;
}
}
I initialize this class as let myClass = new Korisnik(1);
When I try to get naziv() It returns nothing. I have tested it and when I alert this.IME from inside success code it has value but outside it doesn't. I have read and tried from this question but anything from there is not working for some reason. What to do?
Js getters aren't functions, so you need to access it as myClass.naziv
The other problem you have is that your success function isn't running in the same scope as the rest of your function.
You can use a fat-arrow function to ensure you have the right scope.
success: result =>
{
var arr = result.split('|');
this.IME = arr[0];
this.UNIQUE_KEY = arr[1];
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I have the following javascript class similar to this:
class ModalFormButton {
constructor() {
this.contactForm = new ContactForm();
let utils = new Utils();
this.$signupModal = $(utils.getModalTmpl());
}
loadContactForm() {
this.$signupModal.modal();
this.contactForm.load();
}
contactBtnHandler(e) {
e.preventDefault();
let utils = new Utils();
var $t = $(this),
$modalTitle = $t.data('modal-title'),
$modalFormId = $t.data('modal-form-id');
$('body').append(this.$signupModal);
this.$signupModal.find('.modal-title').html($modalTitle);
this.$signupModal.find('.modal-body').load($t.attr('href') + ' #' + $modalFormId,this.loadContactForm);
};
registerHandlers() {
$('.modal-form-btn').click(this.contactBtnHandler);
};
load() {
this.registerHandlers();
};
}
My problem is that when contactBtnHandler is called I don't have access to class properties because the context belongs to modal-form-btn.
I know I can solve this using an arrow function, but I am wondering about if its possible to separate in a function the logic in the callback (here is a short example but I have longer functions) in a way similar to the one I am using.
Thanks
You can try binding "this" to your class in your callback handler
registerHandlers() {
$('.modal-form-btn').click(this.contactBtnHandler.bind(this) );
};
One could do:
getHandler (){
return e => {
//this is ModalFormButton
};
}
And then:
$('.modal-form-btn').click(this.getHandler());