使用"this"作为功能?

Emm*_*myS 6 javascript this

我用一条我不理解的行继承了一些代码.

function updateQty () {
        obj.find('.inputAmount').html(qty);
        input.val(qty);

        $.each(change_actions, function() {
            this(qty);
        });
    }
Run Code Online (Sandbox Code Playgroud)

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

Nea*_*eal 5

this在内部$.each指的是您正在循环的当前对象.

该对象必须是一个函数才能传递一些东西.


Bra*_*tie 3

作者使用绑定设置了自己的事件,因此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);
});
Run Code Online (Sandbox Code Playgroud)

结果:

// 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
Run Code Online (Sandbox Code Playgroud)

将其想象为click事件以及如何通过绑定到 来添加订阅$('element').click()。每次发生点击时,都会触发任何订阅的事件。