1

I have this "class":

function BooleanAssoc(keyNames) {
    this.assoc = {};
    $.each(keyNames, function(i, val) {
        this.assoc[val] = false;
    });
};

I use it like this:

var signUpStates = new BooleanAssoc([
    "CNPJ", 
    "PASSWORDS", 
    "ADDRESS", 
    "GENERAL_FIELDS", 
    "STATE", 
    "CITY", 
    "SEGMENT", 
    "PRODUCT",
    "EMAIL",
    "TERMS"
]);

I don't understand why I get a TypeError. Perhaps it's my mind that is too "pythonic". I create a dictionary ("Associative Array"), I iterate over a list of strings and create the keys and assign their values accordingly. What am I doing wrong??

1
  • Try binding the callback to $.each to this: $.each(key...(i, val){}.bind(this)). Commented Dec 1, 2015 at 4:07

3 Answers 3

4

Your this is not the this you expect.

Try:

function BooleanAssoc(keyNames) {
  this.assoc = {};

  $.each(keyNames, function(i, val) {
    this.assoc[val] = false;
  }.bind(this));
};

ES5 environments you can just use .forEach too. If using ES6, you can use arrow functions which do not bind the this and use the parent scope:

function BooleanAssoc(keyNames) {
  this.assoc = {};

  keyNames.forEach(val => {
    this.assoc[val] = false;
  });
};

You can also do the following, although it is often considered to not be a best practice as it unnecessarily introduces variables into the scope. However, if you're in an environment like ES3, and where you cannot use shims to add ES5 features, the following will work:

function BooleanAssoc(keyNames) {
  var self = this;
  this.assoc = {};

  $.each(keyNames, function(i, val) {
    self.assoc[val] = false;
  });
};
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

function BooleanAssoc(keyNames) {
    this.assoc = {};
    $.each(keyNames, function(i, val) {
        this.assoc[val] = false;
    }.bind(this));
};

Comments

0

I think it is an issue with the context. Inside each this refers to the current value not the context of the class BooleanAssoc.

function BooleanAssoc(keyNames) {
    var self = this;
    self.assoc = {};
    $.each(keyNames, function(i, val) {
        self.assoc[val] = false;
    });
};

Try above one instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.