简体   繁体   English

如何在对象文字中使用“ this”?

[英]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). 我创建了一种机制,可以使用jquery通过AJAX访问给定的资源(用户,帖子等),并且可以正常工作,但是我希望能够使用this关键字,而不是例如Resource.active_filters ,我会写this.active_filters (参见代码)。 However, when I use it like that, it refers to the methods object instead of the Resource object. 但是,当我这样使用它时,它是指methods对象而不是Resource对象。 How do I make it so that it refers to the Resource object? 如何使它引用Resource对象?

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 () {}
};

That's how the binding will be unless you define an ES6-style class or define that function at the top-level. 除非您定义ES6样式的类或在顶层定义该函数,否则绑定将是这样。

You can always write a classic class: 您可以随时编写经典类:

function Resource() {
  // ...
}

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

Or you can define an ES6 one: 或者,您可以定义一个ES6:

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

These two styles are a lot more conventional than the approach in your question. 这两种样式比您问题中的处理方法更加传统。

It looks like this is some API you are writing that will be invoked by some other code. 看起来这是您正在编写的一些API,将由其他一些代码调用。

When you invoke this API, call reset like this: 调用此API时,请像这样调用reset

reset.call(Resource)

This will call the reset function with the Resource object's context. 这将使用Resource对象的上下文调用reset函数。

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call 更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM