M. Mar
M. Mar

Reputation: 137

How do I use `this` in my object literal?

Im creating a mechanism whereas I can access a given resource (users, posts, etc) through AJAX using jquery, and it works and stuff, BUT I want to be able to use the this keyword, instead of for example Resource.active_filters, so I would write this.active_filters (see code). However, when I use it like that, it refers to the methods object instead of the Resource object. How do I make it so that it refers to the Resource object?

Here is the code:

var Resource = {
  options: {},
  active_filters: [],
  ready_filters: [],
  ready_count: 0,
  group_items: [],
  init: function () {},
  methods: {
    reset: function () {
      Resource.active_filters = [];
      Resource.ready_filters = [];
      Resource.ready_count = 0;
    },
  },
  bindEvents: function () {}
};

Upvotes: 0

Views: 99

Answers (2)

tadman
tadman

Reputation: 211590

That's how the binding will be unless you define an ES6-style class or define that function at the top-level.

You can always write a classic class:

function Resource() {
  // ...
}

Resource.prototype.reset = function() {
  this.active_filters = [ ];
  // ...
}

Or you can define an ES6 one:

class Resource {
  reset() {
    this.active_filters = [ ];
    // ...
  }
}

These two styles are a lot more conventional than the approach in your question.

Upvotes: 4

Jonathan.Brink
Jonathan.Brink

Reputation: 25383

It looks like this is some API you are writing that will be invoked by some other code.

When you invoke this API, call reset like this:

reset.call(Resource)

This will call the reset function with the Resource object's context.

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Upvotes: 1

Related Questions