在javascript继承中extend算是一个比较给力的函数,似乎就是它实现了js中各种class及对象间的继承,可重用度极高,所以特收集珍藏下来,以供以后参阅。
目前主要收集了两个版本的extend函数,如下代码所示:
1.
/** * 版本 1 * * @param destination * @param source * @returns */ function extend(destination, source) { var value = null; var property = null; if (destination && source) { for (property in source) { value = source[property]; if (value !== undefined) { destination[property] = value; } } if (source.hasOwnProperty && source.hasOwnProperty('toString')) { destination.toString = source.toString; } } return destination; }
2.
/** * 版本 2 * * @param destination * @param source */ function extend(destination, source){ var value = null; var property = null; if (destination && source) { for (property in source) { value = source[property]; if (value !== undefined) { destination[property] = (typeof(value) == 'object' && !(value.nodeType) && !(value instanceof Array)) ? extend({}, value) : value; } } if (source.hasOwnProperty && source.hasOwnProperty('toString')) { destination.toString = source.toString; } } return destination; }
另外还有下面这样的一种写法:
/** * 版本 3 * * @param destination * @param source * @returns */ function extend(destination, source) { var value = null; var property = null; if (destination && source) { for (property in source) { value = source[property]; if (value !== undefined) { destination[property] = value; } } var sourceIsEvt = typeof window.Event == "function" && source instanceof window.Event; if (!sourceIsEvt && source.hasOwnProperty && source.hasOwnProperty('toString')) { destination.toString = source.toString; } } return destination; }
上面的这个版本的extend函数主要是多了一句:var sourceIsEvt = typeof window.Event == “function” && source instanceof window.Event;
目前多了的这一句,不是很理解,望知道的童鞋,留言相告啊!这一句到底是用来判断神码的?
给力!学习一下!