Object.create
原理:创建对象,并且现有的对象来提供新创建的对象的proto。
function objectCreate(fn){
function Fn(){};
Fn.prototype = fn;
return new Fn();
}
new
原理:创建实例对象,方法执行并让this指向该实例对象,分析返回的结果。
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
用于检测构造函数prototype 属性是否出现在某个实例对象的原型链上。
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是传一个数组。
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不是立即执行,属于柯里化函数思想。
Function.prototype._bind = function(contxt,...args){
return (...innerArgs)=>{
this.call(contxt,...args.concat(...innerArgs));
}
}
function myName(){
console.log(this.a);
}
myName();
myName._bind(obj)();