Object.create
原理:創(chuàng)建對象,并且現(xiàn)有的對象來提供新創(chuàng)建的對象的proto怀酷。
function objectCreate(fn){
function Fn(){};
Fn.prototype = fn;
return new Fn();
}
new
原理:創(chuàng)建實例對象稻爬,方法執(zhí)行并讓this指向該實例對象,分析返回的結(jié)果蜕依。
function _new(fn,...args){
let obj = Object.create(fn.prototype);
let result = fn.call(obj,...args);
if(typeof result==="object"&&result!==null){
return result;
}
return obj;
}
instanceof
用于檢測構(gòu)造函數(shù)prototype 屬性是否出現(xiàn)在某個實例對象的原型鏈上桅锄。
function _instanceof(a,b){
if(typeof a!=="object"||a===null){
return false;
}
let pro = Object.getPrototypeOf(a);
while(true){
if(pro==null) return false;
if(pro==b.prototype){
return true;
}
pro = Object.getPrototypeOf(pro);
}
}
console.log(_instanceof(new String("111"),String));//true
call,apply
都是改變this,不同的是傳參不同,call是一個一個傳笔横,apply是傳一個數(shù)組竞滓。
Function.prototype._call=function(contxt,...args){
if(typeof this!=="function"){
throw Error("this is not function");
}
contxt = contxt||window;
if(typeof contxt!=="object"||typeof contxt!=="function"){
if(typeof contxt==="bigint"||typeof contxt==="symbol"){
contxt = Object(contxt);
}else{
contxt = new contxt.constructor(contxt);
}
}
let key = Symbol("key");
contxt[key] = this;
let result = contxt[key](...args);
delete contxt[key];
return result;
}
var a = '小紅';
let obj = {
a:'小白',
myName:function(){
console.log(this.a);
}
}
function myName(){
console.log(this.a);
}
myName(); //小紅
myName._call(obj);//小白
bind
bind和call,apply都是改變this,不同的是bind不是立即執(zhí)行吹缔,屬于柯里化函數(shù)思想。
Function.prototype._bind = function(contxt,...args){
return (...innerArgs)=>{
this.call(contxt,...args.concat(...innerArgs));
}
}
function myName(){
console.log(this.a);
}
myName();
myName._bind(obj)();