小编Dim*_*off的帖子

在setTimeout上更改匿名函数的范围会导致奇怪的警告

这让我感兴趣的纯粹是研究和个人发展.我有一组命名空间的函数/变量.

在1个函数中我需要通过setTimeout调用另一个函数但是将范围保持为'this'.我正在努力解决这个问题,似乎无法在setTimeout运行时绑定它.

var foo = {
    ads: ["foo","bar"],
    timeDelay: 3,
    loadAds: function() {
        var al = this.ads.length;
            if (!al)
                return; // no ads

            for(var i = 0; i < al; i++) {
                setTimeout(function() {
                    this.scrollAd(this.ads[i]);
                }.apply(this), this.timeDelay * 1000);
            }
        },
        scrollAd: function(adBlock) {
            console.log(adBlock);

        }
    };
};
Run Code Online (Sandbox Code Playgroud)

.apply(this)DOES更改范围,因为console.log输出正确的对象,但它会立即运行该函数,然后在回调保持为空时出现异常/警告:

useless setTimeout call (missing quotes around argument?)
Run Code Online (Sandbox Code Playgroud)

这样做有一种优雅的方式吗?我知道我能做到

var _this = this;
Run Code Online (Sandbox Code Playgroud)

_this在anon回调中引用.例如,在mootools我会用.bind(this)...

不,因为这涉及动画,我不想" "在字符串周围使用,因为它需要进行评估并会影响性能......

javascript scope

3
推荐指数
1
解决办法
5681
查看次数

mootools"这"在每个?

可能误解了一些简单的东西,但我似乎无法让它发挥作用.

我想:通过"wrapper"中的每个img元素,并从title属性中删除所有html(使用来自mootools的stripTags()更多).我收到错误:

"this.get不是一个函数"

这是代码:

$('wrapper').getElements('img').each(function() {

    var oldAlt = this.get('title').stripTags();
    this.setProperty('alt', oldAlt);

});
Run Code Online (Sandbox Code Playgroud)

提前致谢

javascript mootools

1
推荐指数
1
解决办法
4517
查看次数

在mootools中调用没有上下文的.fireEvent()

以下几行有什么想法吗?

什么样的活动是"Popup"在这里?

fireEvent('Popup','ok');
Run Code Online (Sandbox Code Playgroud)

javascript mootools

1
推荐指数
1
解决办法
1401
查看次数

Mootools什么时候使用Function.prototype.bind

我有一个非常基本的问题,我找不到答案,我确实检查了mootools网站,但我还没有完全掌握这个概念:

在mootools中你有一个函数.bind(),它可以按如下方式使用:

function customFunction () {
    this.setStyle('color','blue');
}

var boundFunction = customFunction.bind(myElement);
boundFunction(); //Now the color of the element is changed to red

// To show how bind works the following example:
var myBoundFunction = myFunction.bind(anyVar);
// is roughly equivalent with
var myBoundFunction = function(){
    return myFunction.call(this);
};
Run Code Online (Sandbox Code Playgroud)

但为什么不这样做呢?

function customFunction (parameter) {
    parameter.setStyle('color','blue');
}

customFunction(myElement);
Run Code Online (Sandbox Code Playgroud)

这似乎更有效率?

我的一个大问题是:使用.bind()会是一个好习惯,为什么会这样?

javascript mootools

1
推荐指数
1
解决办法
219
查看次数

标签 统计

javascript ×4

mootools ×3

scope ×1