1. 安全的类型检测
Object.prototype.toString.call(value) // '[object Array]'
2.作用域安全的构造函数
function Person(name) { if (this instanceof Person) { this.name = name } else { return new Person(name) } }
继承
function Polygon(sides) { if (this instanceof Polygon) { this.sides = sides this.getArea = function() { return 0 } } else { return new Polygon(sides) } } function Rectangle(width, height) { Polygon.call(this, 2) //这里只是简单用Polygon给this添加一些属性而已的操作 this.width = width this.height = height this.getArea = function() { return this.width * this.height } } Rectangle.prototype = new Polygon() // 指定原型会使instanceof代码生效
3. 惰性载入函数
(1)第一次调用时覆盖原函数
function createXHR() { if (typeof XMLHttpRequest !== 'undefined') { createXHR = function() { return new XMLHttpRequest() } } else if (typeof ActiveXObject !== 'undefined') { return new ActiveXObject('Microsoft.XMLHTTP') } else { createXHR = function() { throw new Error('No XHR object available') } } }
(2)使用立即执行函数直接给指定函数
const createXHR = (function() { if (typeof XMLHttpRequest !== undefined) { return function() { return new XMLHttpRequest() } } else if (typeof ActiveXObject !== 'undefined') { return function() { return new ActiveXObject('Microsoft.XMLHTTP') } } else { return function() { throw new Error('No XHR object available') } } })()
4. 函数绑定
var handler = { msg: 'Event handled', handleClick: function(event) { console.log(this.msg, event.type) } } var btn = document.getElementById('my-btn') window.addEventListener(btn, 'click', handler.handleClick.bind(handler))
5. 函数柯里化
(1)未指定上下文
function curry (fn) { var args = Array.prototype.slice.call(arguments, 1) return function() { var innerArgs = Array.prototype.slice.call(arguments) var finalArgs = args.concat(innerArgs) return fn.apply(null, finalArgs) } } function add(num1, num2) { return num1 + num2 } var curriedAdd = curry(add, 5) console.log(curriedAdd(3))
(2)指定上下文
function curry (fn, context) { var args = Array.prototype.slice.call(arguments, 2) return function() { var innerArgs = Array.prototype.slice.call(arguments) var finalArgs = args.concat(innerArgs) return fn.apply(context, finalArgs) } } function add(num1, num2) { return num1 + num2 } var curriedAdd = curry(add,this, 5) console.log(curriedAdd(3))