javascript - 在原型(prototype)中的 $.ready 中使用 "this"

标签 javascript jquery oop this

如何传入类实例的“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);

最佳答案

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

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

关于javascript - 在原型(prototype)中的 $.ready 中使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5175787/

相关文章:

javascript - 文件对象未定义 NuxtJS AsyncData()

javascript - Bootstrap 响应式布局中的 Ytplayer

javascript - SQLite 错误代码号 1 : Syntax Error

objective-c - iOS : is there a way to use a single class to hold common variables and not break Object Oriented principles?

java - 我对抽象、封装及其关系的理解是否正确?

javascript - 如何从 atob 创建二进制 blob - 当前获取不同的字节

javascript - 使用jquery动画控制大奖html旋转

javascript - 使用点击数据填充另一页上的框

jquery - 从函数返回两个或多个值

java - 正确的图形引用方法?