tags:

views:

155

answers:

5

The entire code snipped is:

var observer = {
  addSubscriber: function(callback) {
    this.subscribers[this.subscribers.length] = callback;
  },
  removeSubscriber: function(callback) {
    for (var i = 0; i < this.subscribers.length; i++) {
      if (this.subscribers[i] === callback) {
        delete(this.subscribers[i]);
      }
    }
  },
  publish: function(what) {
    for (var i = 0; i < this.subscribers.length; i++) {
      if (typeof this.subscribers[i] === 'function') {
        this.subscribers[i](what);
      }
    }
  },
  make: function(o) { // turns an object into a publisher
    for(var i in this) {
      o[i] = this[i];
      o.subscribers = [];
    }
  }
};
+6  A: 

It depends on how it is called. I see it is part of an object literal called observer.

observer.make(o) would mean this == observer.

observer.make.call(otherObj, o) would mean this == otherObj.

new observer.make(o) would make a new object to be this


So it would do something like this.

var model = {
    name: 'bike',
    id: 4,
    gears: 7
};

observer.make(model);

//now model has methods from observer
model.addSubscriber(someListener);
model.publish('gearsChanged');
seanmonstar
so if 'this' behaves like your first example, they could have also written it as: o[i] = o[i]??
Blankman
No, `o[i] = obj[i]`.
Matthew Flaschen
ok I updated the question with the entire snipped, where is obj?
Blankman
`obj` is `observer` here.
Matthew Flaschen
now that you've updated what the object is that owns this function, i changed `obj` to `observer`
seanmonstar
+1  A: 

here is an example of the intended use of this.

Robert Greiner
A: 

the object that invoked the function in which this is contained

plodder
A: 

"this" refers to "observer" assuming that is the object in which it was invoked (and in 99% of cases it is);

so: observer.addSubscriber

in the method addSubscriber, "this" will refer to "observer".

When you have objects within objects (or nodes) it can be confusing to resolve "this":

observer = {
    node: $("myDiv"),
    callIt: function(){
        // note "this.node" - node belongs to observer
        this.node.onclick = function(){
           // "this" now refers to the "node" object
           // onclick was invoked by node
        }
    }
}
mwilcox
A: 

this, is how you refere at the scope of a function. it's the function itsel.!!! this example in prototypejs framework is quite handy.

http://api.prototypejs.org/language/function/prototype/bind/

for example if you the following code.

function foo(){
      //here this is foo
      var x = {}; //object
      var me = this;
      var img = new Image();
      img.load = function(){
         //but here this is img.load.. is the scope of the function =)
         // if you want to use the x object you have to assing this FOO a global variable is why you use me = this;
         me //is foo :P
      }
}
nahum silva