prototype.js里的代码:
Object.extend = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
google doctype里的代码:
/**
* The names of the fields that are defined on Object.prototype.
* @type {Array.<string>}
* @private
*/
goog.object.PROTOTYPE_FIELDS_ = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/**
* Extends an object with another object.
* This operates 'in-place'; it does not create a new Object.
*
* Example:
* var o = {};
* goog.object.extend(o, {a: 0, b: 1});
* o; // {a: 0, b: 1}
* goog.object.extend(o, {c: 2});
* o; // {a: 0, b: 1, c: 2}
*
* @param {Object} target The object to modify.
* @param {Object} var_args The objects from which values will be copied.
*/
goog.object.extend = function(target, var_args) {
var key, source;
for (var i = 1; i < arguments.length; i++) {
source = arguments[i];
for (key in source) {
target[key] = source[key];
}
// For IE the for-in-loop does not contain any properties that are not
// enumerable on the prototype object (for example isPrototypeOf from
// Object.prototype) and it will also not include 'replace' on objects that
// extend String and change 'replace' (not that it is common for anyone to
// extend anything except Object).
for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
key = goog.object.PROTOTYPE_FIELDS_[j];
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
};
可以看出,google doctype多考虑了object的某些属性、方法,确保它们能够真正地被“extend”到新对象里。
参看资料:
本文对比分析了prototype.js和googledoctype中实现的Object.extend方法,详细解析了如何通过该方法扩展对象,特别是在处理Object.prototype中定义的方法时的区别。
76

被折叠的 条评论
为什么被折叠?



