微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 使用“this”作为函数?

我用一条我不理解的行继承了一些代码.
function updateQty () {
        obj.find('.inputAmount').html(qty);
        input.val(qty);

        $.each(change_actions,function() {
            this(qty);
        });
    }

.each函数中究竟发生了什么?我以前从未见过这种(var)这种方式.

解决方法

作者使用绑定设置他们自己的事件,因此change_actions很可能是订阅数量发生某些事情时运行的函数.

尝试这样的事情:

// initialize with a value
var actions = [
    function(x){ console.log('I see a new x: ' + x); }
];

// add actions "later"
actions.push(function(x){ console.log('Yup,a new x: ' + x); });

// Then execute them:
$.each(actions,function(){
  this(4);
});

// add another one still
actions.push(function(x){ console.log(x + ' looks new'); });

// re-iterate over them
// Then execute them:
$.each(actions,function(){
  this(5);
});

结果:

// first iteration (only 2 subscribed events)
[15:56:50.030] "I see a new x: 4"
[15:56:50.030] "Yup,a new x: 4"

// second iteration (Now we have 3,one was added later)
[15:56:50.030] "I see a new x: 5"
[15:56:50.030] "Yup,a new x: 5"
[15:56:50.030] "5 looks new"  // <-- new subscription

把它想象成click事件以及如何通过绑定到$(‘element’)来添加订阅.单击().每次发生点击时,都会触发任何订阅的事件.

原文地址:https://www.jb51.cc/js/151256.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐