giantqtipz giantqtipz - 11 months ago 32
Javascript Question

Passing context "this" from one function into another inside it?

I'm practicing ajax with forms, and.. I guess trying to confuse myself more and more for the sake of learning.

This might not make any sense, but I'm trying to log the first and last name, specifically through the conLog function. But it's showing as undefined because I think the context "this" is not there, and I'm not sure how to set it. I managed to set it inside the ajax however.

So if you open the log, the 2nd line says undefined, while in the first, the input from the first form is logged.

Assuming that's the problem, how do I pass "this" into conLog?

thanks in advance! and I found a few posts with the same question, but sigh... I guess I can't grasp it unless if it's applied to my personal problem (still need to learn to read other people's codes I guess).


<form action="/echo/html/" id="form1" method="post">
First Name:
<input type="text" value="first" id="firstName">
Last Name:
<input type="text" value="last" id="lastName">
<button type="submit" form="form1" value="submit">Submit</button>


function Display(el) {
this.el = el;
this.firstName = this.el.find("#firstName");
this.lastName = this.el.find("#lastName");
var confirmation = this;
this.el.on('submit', function(e) {
$.ajax('/echo/html/', {
success: function() {
console.log('success' + " " + this.firstName.val());
this.conLog(this.firstName.val(), this.lastName.val());
error: function() {
timeout: 3000,
context: confirmation

this.conLog = function(first, last) {
this.first = this.first;
this.last = this.last;
console.log(this.first + " " + this.last);

$(document).ready(function() {


You don't need to pass this. Because you're already passing the first and last parameters. Just use those directly like this:

this.conLog = function(first, last) {
  console.log(first + " " + last);

Note I changed this.first and this.last to just first and last.