“这个”在这个函数中指的是什么?

时间:2010-04-01 19:52:00

标签: javascript

整个代码段是:

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 = [];
    }
  }
};

3 个答案:

答案 0 :(得分:6)

这取决于它的调用方式。我发现它是一个名为observer的对象文字的一部分。

observer.make(o)意味着this == observer

observer.make.call(otherObj, o)意味着this == otherObj

new observer.make(o)会将新对象设为this


所以它会做这样的事情。

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

observer.make(model);

//now model has methods from observer
model.addSubscriber(someListener);
model.publish('gearsChanged');

答案 1 :(得分:0)

“this”指的是“观察者”,假设它是调用它的对象(并且在99%的情况下是它);

所以:observer.addSubscriber

在addSubscriber方法中,“this”将引用“observer”。

如果对象(或节点)中有对象,则解决“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
        }
    }
}

答案 2 :(得分:0)

这就是你如何参考一个函数的范围。这是它的功能。!!!在prototypejs框架中的这个例子非常方便。

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

例如,如果您使用以下代码。

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
      }
}