js相关方法的polyfill
2017-11-13 本文已影响11人
前端收藏家
assign
if(typeof Object.assign != 'function'){
Object.assign = function(target){
'use strict';
if(target == null){
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for(var index = 1, len = arguments.length; index < len; index++){
var source = arguments[index];
if(source != null){
for(var key in source){
if(Object.prototype.hasOwnProperty.call(source, key)){
target[key] = source[key];
}
}
}
}
return target;
}
}
create
if (typeof Object.create !== "function") {
Object.create = function (proto, propertiesObject) {
if (!(proto === null || typeof proto === "object" || typeof proto === "function")) {
throw TypeError('Argument must be an object, or null');
}
var temp = new Object();
temp.__proto__ = proto;
if(typeof propertiesObject ==="object"){
Object.defineProperties(temp,propertiesObject);
}
return temp;
}
}
deepFreeze
function deepFreeze(obj){
var o, key;
Object.freeze(obj);
for(key in obj){
o = obj[key];
if( !(o.hasOwnProperty(key)) || !(typeof o === 'object') || Object.isFreeze( o ) ){
continue;
}
deepFreeze(o);
}
}
is
if(typeof Object.js !== 'function'){
Object.is = function (x, y){
if(x === y){
// +0 != -0
return x !== 0 || 1/x !== 1/y;
}else{
// NaN == NaN
return x !== x && y !== y;
}
}
}