1,new 的过程;
function myNew(func) {
let res = {};
if (func.prototype !== null) {
res.__proto_ = unc.prototype;
}
let ret = func.apply(res, arguments.splice(1));
if ((typeof (ret) === 'object' || typeof (ret) === 'function') && ret !== 'null') {
return ret
}
return res;
}
2,实现JSON.stringify
function jsonStringify(obj) {
let type = typeof (obj);
if (type !== 'object') {
if (type === 'function') {
return;
}
return String(obj)
} else {
let isArr = Array.isArray(obj),arrJson = [];
for (let k in obj) {
let v = obj[k];let type = typeof(v);
if (type !== 'object') {
if (type === 'function') {
v = null;
}
v = String(v)
}else{
v=jsonStringify(v)
}
arrJson.push(isArr?k:(k+':')+v)
}
return (isArr ? '[':'{') + String(arrJson) +(isArr ? ']':'}');
}
}
3,实现JSON.parse
function myParse(str){
return (new Function('return'+str))()
}
4,实现call方法
Function.prototype.myCall=function(content=window){
content.fn = this;
console.log(this,[...arguments].splice(1));
let args=[...arguments].splice(1);
let res = content.fn(...args);
delete content.fn;
return res;
}
5,实现apply方法
function myApply(content=window){
content.fn = this;
console.log(this);
let args=arguments.splice(1);
let res=null;
if(args){
res = content.fn(args);
}else{
res = content.fn();
}
delete content.fn;
return res;
}
6,实现bind方法
Function.prototype.myBind = function myBind(content){
if(typeof(this)!=='function'){
throw new Error(this+'not a function');
}
let fn = this;
let args = [...arguments].splice(1);
let res = function(){
console.log(this);
fn.apply(this instanceof res? this:content,args.concat(...arguments))
}
res.prototype = Object.create(this.prototype);
return res;
}
7,六种继承方式
function A(name){
this.name=name
}
function B(age){
this.age=age
}
//原型链继承
A.prototype = new B();
//构造函数继承
function B(age){
a.apply(this,name);
this.age=age;
}
//组合式继承
function B(age){
a.apply(this,name);
}
B.prototype = new A();
//原型式继承
function B(obj){
let Func = function(){};
Func.prototype=obj;
return new Func()
}
let obj = new A();
let child = B(obj);
//寄生式继承
function B(obj){
let Func = function(){};
Func.prototype=obj;
return new Func()
}
let obj = new A();
function Child(obj){
let res = B(obj);
res.hobby='吃';
return res;
}
//寄生组合式继承
function B(age){
A.apply(this,name);
this.age=age;
}
let Apro = Object.create(A.prototype);
Apro.constructor=B;
B.prototype=Apro;