【问题标题】:Using "this" within $.ready within prototype在原型中使用 $.ready 中的“this”
【发布时间】:2011-07-07 17:48:42
【问题描述】:

如何传入 Class 实例的“this”上下文的变量代理?例如, this.saySomething() 没有做我想做的事。

您对 OOJS 代码组织还有其他建议吗?

// Truveo Video Player Class
function Player(){

    // Player Defaults
    this.opts = {
        volume: 0 // Initial volume settings
    };
}

// Initialize player setup / methods
Player.prototype.init = function(configs){

    // Overwrite defaults with custom configs
    this.opts = $.extend(this.opts, configs);

    $(document).ready(function(){
        this.saySomething();
    });
    $(window).load(function(){
        // do something else
    });
}

Player.prototype.saySomething = function(){
    alert(this.opts.volume);
}

// Create instance for channel surf
var configs = {volume:10};
var cSurf = new Player();
cSurf.init(configs);

【问题讨论】:

  • 我确定你试过了,但请检查 thisalert(this) 是什么,看看发生了什么。

标签: javascript jquery oop this


【解决方案1】:

进入函数前保存this的副本:

var me = this;
$(document).ready(function(){
    me.saySomething();
});

【讨论】:

  • 这行得通,但我很惊讶。我认为创建这样的 var 等同于在其他地方无法访问的私有 var?
  • 另外,在创建类时创建 opts 默认值是否正确?或者我应该在原型调用中这样做吗?
  • @Matrym,是的 var meinit 函数私有的,但是因为 .ready 的处理函数是在 init 中创建的,所以它获得了一个 closure 捕获对init 中每个局部变量的引用。
  • @Matrym,在构造函数中创建opts 是正确的,因为必须为Player 的每个新实例创建一个新的opts 实例。原型是共享的,因此将opts 附加到prototype 将不起作用。
  • 谢谢,您在帮助我迈出 OOJS 步骤方面非常有帮助 :)
【解决方案2】:

除了来自@Box9correct answer,一种可能性是为整个.ready() 调用设置this 的值。

您可以使用jQuery.proxy()[docs] 方法来做到这一点。

$(document).ready( $.proxy(function(){
    this.saySomething();
}, this) );

现在在发送到.ready() 的函数中,它会将您的Player 对象作为this 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-09-30
    • 2011-05-08
    • 1970-01-01
    相关资源
    最近更新 更多