javascript中apply,call,bind方法

来源:互联网 发布:淘宝出名的店铺 编辑:程序博客网 时间:2024/04/28 01:16

apply,call应该是我们比较熟悉的方法,像Math.max.apply(arr),取数组元素中的最大值,Array.prototype.slice.call(obj)把obj变为数组等方法已经说明了apply及call的使用,

这两者在性能上并无区别,只不过在后面参数上有一定差异,apply的参数是数组形式,而call则是单个元素的形式,譬如我们在网上看到的最常见的add.call(sub,3,1)则是成功调用add方法,得到结果4.当然,call方法也在函数中可以实现类似的多继承问题在网上也有类似回答,就不再列举。

那么bind呢,是我们在jquery框架中经常使用的一个函数,用来将某些事件绑定,而在javascript中的使用我们很少见到这个的用法,今天把这个拿出来炒一炒是因为遇到一件比较好玩的题目运到了这个方法。

题目为:

 you have to extend the dictionary with a method, that returns a list of words matching a pattern. This pattern may contain letters (lowercase) and placeholders ("?"). A placeholder stands for exactly one arbitrary letter.

Javascript Example:

var fruits = new Dictionary(['banana', 'apple', 'papaya', 'cherry']);fruits.getMatchingWords('lemon'); // must return []fruits.getMatchingWords('cherr??'); // must return []fruits.getMatchingWords('?a?a?a'); // must return ['banana', 'papaya']fruits.getMatchingWords('??????'); // must return ['banana', 'papaya', 那么这种题目应该怎么样求解呢。我起初想到的是要是可以利用数组中的元素在正则表达式?的位置任意替换就可以了。那么这个正则表达式应该怎么写呢。 pattern = new RegExp('^'+pattern.replace(/\?/g, '.')+'$'); 这个表达式的意思是将?的位置替换成任意字符。然后呢,我没辙了,这个正则表达式求出来应该怎么用,我没有想法,所以看了一下推荐最高的回答,其中发现了bind的踪影,它的解答为: return this.words.filter(pattern.test.bind(pattern)); 其中this.words是dictionary构造函数中的参数。然后发现javascript里面的bind的意思和apply类似,却又不同,它可以改变this的指向,而且起到了函数的作用,而而apply,call则不是,譬如我们是可以这样。var anotherGuySayHello = person.sayHello.bind({ 
name:'Alex', 
job: 'back end C# developer' 
}); 这样子来定义一个函数的,可以直接调用anotherGuySayHello.但是换做call和apply就不可以。
可是,我对于pattern.test.bind(pattern)怎么使用得到true和false还有一点点迷茫,所以大家如果对这个题目有自己的理解就帮忙留言一下啦。


0 0