Skip to content

Instantly share code, notes, and snippets.

@xuanfeng
Last active January 3, 2016 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuanfeng/8397382 to your computer and use it in GitHub Desktop.
Save xuanfeng/8397382 to your computer and use it in GitHub Desktop.
extend()函数:用一个或多个其他对象来扩展一个对象,返回被扩展的对象
// 定义一个扩展函数,用来将第二个以及后续参数复制只第一个参数
// 这里我们处理了IE bug:在多数IE版本中
// 如果o的属性拥有一个不可枚举的同名属性,则for/in循环
// 除非我们先是检测它
var extend = (function(){ //将这个函数的返回值赋值给extend
// 在修复它之前,首先检查是否存在bug
for(var p in {toString: null}){
return function extend(o){
// 如果代码执行到这里,那么for/in循环会正确工作并返回
// 一个简单版本的extend()函数
for (var i=1; i<arguments.length; i++){
var source =arguments[i];
for(var prop in source) o[prop] = source[prop];
}
return o;
};
}
// 如果代码执行到这里,说明for/in循环不会枚举测试对象的toString属性
// 因此返回另一个版本的extend()函数,这个函数显式测试
// Object.prototype中的不可枚举属性
return function patched_extend(o){
for(var i=1; i<arguments.length; i++){
var source = arguments[i];
// 复制所有的可枚举属性
for(var prop in source) o[prop] = source[prop];
// 现在检查特殊属性
for(var j=0; j<protoprops.length; j++){
prop = protoprops[j];
if(source.hasOwnProperty(prop)) o[prop] = source[prop];
}
}
return o;
};
// 这个列表列出了需要检查的特殊属性
var protoprops = ["toString", "valueOf", "constructor", "hasOwnProperty",
"isPrototypeOf", "propertyIsEnumerable", "toLocaleString"];
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment