【问题标题】:How to create classwide pointer to this?如何创建指向此的类范围指针?
【发布时间】:2014-05-29 13:15:13
【问题描述】:

我正在使用 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 指针?

【问题讨论】:

  • 不确定您的意思或该类将如何使用,但 jQuery 使用 bind 在回调中设置 this 的正确值?

标签: javascript class oop this


【解决方案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'
});

【讨论】:

  • click 事件将在同一个班级,而不是在外面。我想定义类范围变量并在所有方法中访问它,甚至在任何类方法中的click 事件中访问它。
【解决方案2】:

“this”关键字总是指向它被实例化的环境。例如:

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

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

me.name 将返回“myName”,you.name 将返回“yourName”。

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

【讨论】:

    【解决方案3】:

    通过添加这个方法,你可以做到这一点

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

    【讨论】:

    • 这是一个好的开始,但 self 只能在 addHandler 方法中访问。如何在不定义每个方法的情况下使其成为全类?
    • 我认为没有解决方案。
    • 是否意味着没有创建新的作用域来保存 Simple JavaScript Inheritance 中的局部变量?
    • 局部变量是什么意思?就你而言,班级成员?
    • 这就是闭包在 JavaScript (stackoverflow.com/questions/111102/…) 中的工作原理。
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2023-03-12
    • 2016-07-25
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多