【问题标题】:Accessing the parent object of a function in Javascript [duplicate]在Javascript中访问函数的父对象[重复]
【发布时间】:2014-07-05 12:18:00
【问题描述】:

我在这里有这个函数,它获取对象的各个部分并延迟连续照亮它们(它将元素的不透明度切换为 1,然后将前一个元素的不透明度切换为 0 以连续照亮它们)。

问题是我无法使用 this 关键字访问 illuminateInternal 函数中的父对象部分。

这会阻碍我的对象的任何可能重用,因为我将拥有 ma​​leBackNoZoomma​​leBackFullZoom 对象。

当我重用我的对象时,我不想更改 illuminateInternal 函数的变量名,所以我也想在 illuminateInternal 函数中使用类似 this 关键字的东西。

maleBackNoZoom = {

    parts:{
    armsRight: findItemById("29") ,
    armsLeft: findItemById("28"),
    legsRight: findItemById("21"),
    legsLeft: findItemById("22"),
    back: findItemById("24"),
    buttocks: findItemById("23"), 
    neck: findItemById("26"),
    head: findItemById("27")
     },

  illuminate: function() {
    var propertiesToIlluminate = [], prop, illuminateInternal, i = 0, delay = 200, intervalId;
    for (prop in this.parts) {
        propertiesToIlluminate.push(prop);
    }

    illuminateInternal = function () {
        var property = propertiesToIlluminate[i];
        var previousProperty = propertiesToIlluminate[i-1];
        maleBackNoZoom.parts[property].opacity = 1;
         console.log(previousProperty);
        if (typeof previousProperty !== 'undefined'){
        maleBackNoZoom.parts[previousProperty].opacity = 0;
         }

        paper.view.update();
        i++;

        if (i === propertiesToIlluminate.length) {

            maleBackNoZoom.parts[property].opacity = 0;
            clearInterval(intervalId);
            setInterval(function(){paper.view.update()},delay);
        }
    };
    intervalId = setInterval(illuminateInternal, delay);
}  
}

【问题讨论】:

  • 在您的illuminateInternal 函数之外定义var self = this 并在您的内部函数中调用self.parentFunctions

标签: javascript oop object this


【解决方案1】:

您可以在illuminate 方法中定义局部变量,该变量将存储对其对象的引用。然后你可以把它作为this的别名。

var self = this;

illuminateInternal = function () {
    ..
    self.parts[property].opacity = 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2013-07-01
    相关资源
    最近更新 更多