0

为简单起见并满足需求,代码已被删除:
我知道这些方法毫无意义。我只想知道什么是非法的,以及如何以一种我能在下面描述的最好的方式一起使用方法。

问题来自 bindContentOverlay 方法:

this.setContentOverlayHeight is not a function
this.setContentHeight is not a function

这里有一些类似于我正在使用的东西:
使用这种类型的风格的任何关于 OOP 的指针也非常受欢迎。

$(document).ready(function(){
    var p = new Properties();
    p.bindContentOverlay();
});

var Properties = function()
{
    this.initialize();
}

Properties.prototype.initialize = function()
{
    this.menu = {"#power" : null,"#services" : "#services_menu","#cashback" : null,"#schedule" : "#schedule_menu"};
    this.a = 22;
    this.b = 33;
}

Properties.prototype.getHeights = function()
{
    this.initialize();
    this.q = this.a;
    this.w = this.b;
}

Properties.prototype.setContentOverlayHeight = function()
{   
    this.getHeights();
    alert(this.q);
}

Properties.prototype.setContentHeight = function()
{
    this.getHeights();
    alert(this.w);
}


Properties.prototype.bindContentOverlay = function()
{
    for(var i in this.menu)
    {
        (function(x, y) {
             $(x+','+y).hover(
                 function () {
                    console.log(x);
                    this.setContentOverlayHeight();
                 },
                 function () {
                    this.setContentHeight();
                    console.log(y);
                 }
            );
        })(i, this.menu[i]);
    }   
}
4

2 回答 2

2

this在悬停回调中指的是悬停的元素,而不是当前Properties对象。

最简单的解决方法是将本地引用绑定到this的顶部.bindContentOverlay

Properties.prototype.bindContentOverlay = function()
{
    var self = this;
    ...
}

然后self.setContentOverlayHeight()在回调中使用。

于 2012-10-10T06:59:10.600 回答
1

每当您在函数中定义函数时,您都可能会丢失上下文( 的值this)。

问题是您如何编写该bindContentOverlay方法。当那些最深的功能执行时,this不是你所期望的。

防止这种情况的最简单方法是保存this到局部变量并改用它。

Properties.prototype.bindContentOverlay = function()
{
    // Save "this" to local var, and use the var instead for any inner functions.
    var instance = this;

    for(var i in this.menu)
    {
        (function(x, y) {
             $(x+','+y).hover(
                 function () {
                    console.log(x);
                    instance.setContentOverlayHeight();
                 },
                 function () {
                    instance.setContentHeight();
                    console.log(y);
                 }
            );
        })(i, instance.menu[i]);
    }   
}
于 2012-10-10T07:01:14.833 回答