开发者

bind combined with delay

开发者 https://www.devze.com 2023-01-24 11:06 出处:网络
Which is better some_func.bind(this,arg1,arg2,arg3).delay(4); or some_func.bind(this).delay(4,arg1,arg2,arg3);

Which is better

some_func.bind(this,arg1,arg2,arg3).delay(4);

or

some_func.bind(this).delay(4,arg1,arg2,arg3);

I know that both ways will wrap things up in two layers but suppose one of the arguments lets say arg1 is an object that is a reference from the current context,开发者_如何学Go e.g. var arg1 = this.some_obj. Now because of all the business with pass by value, pass by reference, and function scoping will the second way not be able to recover arg1 because when delay is called its context is the global object.


It's easy enough to test and both ways work well.

function object() {
    this.foo = function(arg) {
        document.write(this.bar+' was born on '+arg);
    }
    this.bar = 'Bob';
    this.dob = new Date();
    foo.bind(this, this.dob).delay(4);
    this.dob.setFullYear(1971);
}
object(); // start the delay

The date of birth is an object and so is passed by reference. You can see this happen because the year is set after the call and the delayed write shows a date in the past.

Now change the important line to foo.bind(this).delay(4, this.dob) and it still works!

Here's the really hard question. Why does foo.delay.call(this, 4, this.dob) not work?

0

精彩评论

暂无评论...
验证码 换一张
取 消