使用“这个”在 $.ready 内原型内
如何传入类实例的“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);
How do I pass in a variable proxy of the "this" context of the Class instance? For example, this.saySomething() isn't doing what I'd like it to.
Do you have any other recommendations on OOJS code organization?
// 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在进入函数之前保存
this
的副本:Save a copy of
this
before entering the function:除了正确答案之外https://stackoverflow.com/users/405143/box9">@Box9,一种可能是为整个
.ready()< 设置
this
的值/代码> 调用。您可以使用
jQuery.proxy()
[文档] 方法。现在,在发送到
.ready()
的函数中,它将把您的Player
对象作为this
的值。In addition to the correct answer from @Box9, one possibility would be to set the value of
this
for the entire.ready()
call.You can do this with the
jQuery.proxy()
[docs] method.Now in the function that's sent to
.ready()
it will have yourPlayer
object as the value ofthis
.