1.判断数据类型时,我们最经常用typeof判断某一数据类型,缺点不能很好判断null,数组,正则,函数,因为这几个都是返回object,而Object.prototype.toString().call(value)很好解决了这个问题
var array = [1,2,3], nullobj = null, fn = function () {alert(1)}, reg = /^[1-4]$/; console.log(Object.prototype.toString.call(array)) // '[object Array]' console.log(Object.prototype.toString.call(nullobj)) // '[object Null]' console.log(Object.prototype.toString.call(fn)) // '[object Function]' console.log(Object.prototype.toString.call(reg)) // '[object RegExp]'
2.函数绑定
例子2.1:
var btn = document.getElementById('btn') var handler = { color:'red', handleclick: function () { console.log(this.color) } } btn.onclick = handler.handleclick // undefined,执行时this指的是DOM按钮
上面例子2.1中,this指向DOM按钮,要想this指向handler,可用闭包解决,如下例子2.2:
例子2.2:
var btn = document.getElementById('btn') var handler = { color:'red', handleclick: function () { console.log(this.color) } } btn.onclick = function () { handler.handleclick() // red,执行时this指的是handler }
此外,还可以写一个bind函数,可以将函数绑定到某个环境中,如下例子2.3
例子2.3:
var btn = document.getElementById('btn') var handler = { color:'red', handleclick: function (ev) { console.log(ev.type) console.log(this.color) } } function bind(fn, context) { return function() { return fn.apply(context,arguments) // 注意这里的arguments指的是内部函数的arguments,不是bind的 } } btn.onclick = bind(handler.handleclick,handler) // 输出click和red
原生的bind与上面方法类似,都需要传入作为this的对象