Using a function within another function, in a class - Javascript

class Form {
	ajax(method = '', dtype = '', path = '', data = '') {
		$.ajax({
			type: method,
			dataType: dtype,
			url: path,
			data: getstarteddata,
			success: function(res) {
				if (res == 200) {
					$("#btnsend").attr("disabled", true).val("Subscribed");
					$(".sucess-message").text('Way to go πŸš€');
				} else {
					$("#btnsend").attr("disabled", false).val('Subscribe');
					$(".error-message").text('oops! failed try ❌')
				}
			},
			error: function (res) {
				$(".error-message").text('OMG! ❌ β€” '+ JSON.stringify(res));
				return false;
			}
		});
	}

	grabmail(email = ''){
		if (email.split("@").length != 2) {
			$("#btnsend").attr("disabled", false).val('Subscribe');
			$(".error-message").text('uhmm! email not right')
		} else {
			this.ajax('POST', 'json', './app/newslater', {mail: email});
		}
	}

	submit(){
		$("#newslatter").on('submit', function(e) {
			e.preventDefault();
			let email = $(".email-input").val();
			this.grabmail(email);
		})
	}
}

form = new Form();
form.submit();

I get Uncaught TypeError: this.grabmail is not a function. I’m not sure, what’s wrong

Because you’re passing grabmail inside .on method callback, where this value will refer to $("#newslatter") element. In order to make this happen you need to convert your callback to arrow function - that would solve your issue, so:

submit() {
  $("#newslatter").on('submit', (e) => {
    e.preventDefault();
    let email = $(".email-input").val();
    this.grabmail(email);
  })
}
1 Like