深拷贝
function cloneDeep(obj,hash = new WeakMap()){
if(obj==null || typeof obj !== 'object') return obj;
if(obj instanceof Date) return new Date(obj);
if(obj instanceof RegExp) return new RegExp(obj);
if(hash.get(obj)) return hash.get(obj);
var cloneObj = new obj.constructor;
hash.set(obj,cloneObj);
for(var key in obj){
if(obj.hasOwnProperty(key)){
cloneObj[key] = cloneDeep(obj[key],hash);
}
}
return cloneObj;
}
var obj = {name:'wyy',outer:{inner:'test'}};
obj.o = obj;
var clone = cloneDeep(obj);
console.log(obj,clone);
模拟new
function create(){
var Con = [].shift.call(arguments);
obj = Object.create(Con.prototype);
var ret = Con.apply(obj,arguments);
return ret instanceof Object?ret:obj;
}
function Car(color){
this.color = color;
return {a:12}
}
var obj = create(Car,'red')
模拟bind
Function.prototype.mybind = function(context){
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = [].slice.call(arguments,1);
var fBind = function(){
var innerArgs = [].slice.call(arguments);
self.apply(this instanceof fBind?this:context,args.concat(innerArgs));
}
fBind.prototype = Object.create(this.prototype);
return fBind;
}
var obj = {
name:'wyy'
}
function bar(color){
this.color = color;
console.log(this.color,color);
}
var barFn = bar.mybind(obj,'red');
new barFn();