如何创建类的全范围指针?

时间:2014-05-29 13:15:14

标签: javascript class oop this

我正在使用John Resig的Simple JavaScript Inheritance。 我知道我可以使用this变量在方法之间共享值:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  }
});

我想创建一个指向this的指针,以便以后不会被覆盖:

$('#id').click(function() {
  // this now points to selector
});

如何创建让我们说that = this的指针可以在全国范围内访问?

3 个答案:

答案 0 :(得分:1)

您可以使用' .apply()'

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },

  setDancing = function(isDancing) {
    this.dancing = isDancing;
  }
});

var p = new Person();

$('#id').click(function() {
  p.setDancing.call(p, NEWVALUE);
  // 'this' will point to 'p' in the function 'p.setDancing'
});

答案 1 :(得分:0)

' this'关键字始终指向实例化的环境。例如:

function Obj(name)
{
this.name = name;
}

var me = new Obj('myName');
var you = new Obj('yourName');

me.name将返回' myName'和you.name将返回' yourName'。

您只能在创建它的环境中为其指定指针,如果它在该环境中没有引用任何内容,则指向全局窗口。当你实例化一个init类型的对象时,'这个'指针将指向isDancing。

答案 2 :(得分:0)

通过添加此方法,您可以执行此操作

addHandler: function() {
    var self = this;
    $('#id').click(function() {
      // self now points to this
    });
}