1

I'm really new in emberJS,I see many 'this.' in the official Guides . In ember Object model I know 'this.' represent the object itself,such as follow:

 var obj = Ember.Object.extend({
  baz: {
    foo: 'BLAMMO',
    bar: 'BLAZORZ'
  },

  something: Ember.computed('baz.{foo,bar}', function() {
    return this.get('baz.foo') + ' ' + this.get('baz.bar');
  })
});

this means obj itself,but in other case,such as models like follow:

export default Ember.Route.extend({
  model() {
    this.store.push({
      data: [{
        id: 1,
        type: 'album',
        attributes: {
          title: 'Fewer Moving Parts',
          artist: 'David Bazan',
          songCount: 10
        },
        relationships: {}
      }, {
        id: 2,
        type: 'album',
        attributes: {
          title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time',
          artist: 'Bon Iver',
          songCount: 2
        },
        relationships: {}
      }]
    });
  }
});

what is 'this' really represent?

Patsy Issa
  • 10,623
  • 3
  • 52
  • 72
foolishfox
  • 127
  • 1
  • 1
  • 7

3 Answers3

2

this is totally dependant on where and what and how a function was called or object created. The value of this is a construct of javascript itself and not ember. I would strongly encourage you to read more about this in javascript. Its really fundamental to becoming a good javascript developer.

Here's some good resources that helped me:

As for the code in your original question, the vast majority of objects in Ember extend the base ember object, and Route is no exception. So in the lower block of code, this is referring to the route object that the model() function is defined in.

Community
  • 1
  • 1
xcskier56
  • 591
  • 2
  • 11
  • 1
    Although you should probably mention that `this` in an action refers to the object that contains the `actions` hash, not the `actions` hash itself as one would normally expect with default JS behavior. –  Aug 28 '16 at 06:34
0

Ember tries to always give a a this that is the current object in almost all cases. In actions its the normal object as well, same for computed properties, observers and so on.

I think the only totally different thing is the router DSL.

So in both your example this is the current object. In the second you are just able to call this.store because the store is injected into the route.

Lux
  • 16,183
  • 3
  • 36
  • 64
  • your idea is correct,I have read many articles and finally I find 'this' in javascript is quite different from java.'this' is passed as param of the function,so it depends on the context of itself. – foolishfox Oct 12 '16 at 02:05
0

Like xcskier mentioned, this depends on the context in which you are in. Why don't you examine your "this" yourself by doing something like

console.log(this);
Tom Mathew
  • 134
  • 1
  • 8