JS instanceof call bind 等源码

instanceof

/*
*params:example(要检测的实例),classFunc(要检测的类)
*
*
*/
function instanceof(example,classFunc){
	let classPrototype = classFunc.prototype;
		proto = Object.getPrototypeOf(example);
	while(true){
		//到了Object.prorotype.__proto__ = null
		if(proto === null){
			return false
		}
		if(proto === classPrototype){
			return true
		}
		proto = Object.getPrototypeOf(proto);
	}
}

Promise

function MyPromise(excutor){
	if(typeof executer !== 'function'){
			// 参数合法校验
			throw new Errow('MyPromise resolve' + executer + 'is not a function')
	}
	_this = this;
	// 设置初始值
	this.PromiseStatus = "padding";
	this.PromiseValue = undefined;
	this.resolveFunc = function(){};
	this.rejectFunc = function(){};
	
	change(status,value){
		if(_this.PromiseStatus !== "padding") return;
		_this.PromiseStatus = status;
		_this.PromiseValue = value;
		var delayTimer = setTimeout(function(){
			clearTimeout(delayTimer);
			delayTimer = null;
			status === 'resolved || fulfilled' ? _this.resolveFunc.call(_this,value):_this.rejectFunc.call(_this,value)
		})
	}
	try{
		excutor(function resolve(value){
		change("resolved",value)},
		function reject(reason){
		change("rejected",reason)})
	}catch(err){
		change("rejected",err.message)
	}	
}

MyPromise.prototype.then = functino then(resolveFunc,rejectFunc){
	// 参数不传默认值的处理:目的是实现状态的顺延
	if(typeof resolveFunc!== "function"){
		resolveFunc = function(value){
			return MyPromise.resolve(value)
		}
	}
	if(typeof rejectFunc!== "function"){
		rejectFunc = function(reason){
			return MyPromise.reject(reason)
		}
	}
	_this = this;
	// 我们返回的新实例的成功和失败(执行resolve/reject)
    // 由resolveFunc/rejectFunc执行是否报错来决定(或者返回值是否为新的MyPromise实例来决定)
	return new MyPromise(function (resolve,reject){
		_this.resolveFunc = function (){
			try{
				var x = resolveFunc.call(_this, value);
                    x instanceof MyPromise ? x.then(resolve, reject) : resolve(x);
                }catch(err){
                	reject(err.message)
                }
		};
		_this.rejectFunc = function (reason) {
                try {
                    var x = rejectFunc.call(_this, reason);
                    x instanceof MyPromise ? x.then(resolve, reject) : resolve(x);
                } catch (err) {
                    reject(err.message);
                }
         };
	})
};

MyPromise.prototype.catch = function (rejectFunc) {
        return this.then(null, rejectFunc);
};

// MyPromise当做对象使用
MyPromise.resolve = function(value){
	return new MyPromise(function (resolve){
		resolve(value)
	})
}
MyPromise.reject = function(reason){
	return new MyPromise(function(reject){
		reject(reason)
	})
}

MyPromise.all = function (promiseArr) {
        return new MyPromise(function (resolve, reject) {
            var index = 0,
                values = [];
            for (var i = 0; i < promiseArr.length; i++) {
                // 利用闭包的方式保存循环的每一项索引
                (function (i) {
                    var item = promiseArr[i];
                    // 如果当前项不是Promise:直接算作当前项成功
                    !(item instanceof MyPromise) ? item = MyPromise.resolve(item): null;
                    item.then(function (value) {
                        index++;
                        values[i] = value;
                        if (index >= promiseArr.length) {
                            // 所有的实例都是成功的
                            resolve(values);
                        }
                    }).catch(function (reason) {
                        // 只要有一个失败,整体就是失败的
                        reject(reason);
                    });
                })(i);
            }
        });
    };

toType检测数据类型


```javascript
function toType(obj){
	let type = Object.prototype.toString.call(obj);
	/^\[object ([a-z]+)\]$/i.exec(type)[1].toLowerCase();
}

call

Function.prototype.call = function call(context,...params){
	// context => 最后要改变的函数中的this指向
	// params => 传递给函数的实参信息
	// this => 要处理的函数
	context = context == null ? window : context;
	// 必须要保证context是一个对象
	let contextType = typeof context;
	if(!/^(object|function)$/i.test(contextType)){
		// context = new context.constructor(context); 不适合Symbol/Bigint
		context = Object(context);
	}
	let result;
		key = Symbol('KEY');
	// 把函数作为对象的某个成员值,且唯一,防止修改原始对象的结构值
	context[key] = this ;
	result = context['fn'](...params);
	delete context['fn'];
	return result;
}

new 构造函数

function _new(Func,...args){
	let obj = {};
	obj._proto__ = Func.prototype;
	// IE不支持__proto__,可用以下方法
	// let obj = Object.careat(Function.prototype)
	let result = Func.call(obj,..params);
	if(result !== null && /^(object|function)$/.test(typeof result){
		return result
	}
	return obj;	
}

// 重写Object.create
Object.create = function create(prototype){
	if(prototype == null || typeof prototype !== 'object'){
		throw new Error('');
	}
	// 创建一个类,创建这个类的实例,实例.__proto__ = 类.prototype
	function Temp(){};
	Temp.prototype = prototype;
	return new Temp
}

bind

Function.prototype.bind = function bind(context,...params){
	// this,处理的函数
	// context,要改变的函数中的this指向
	// params,传递的参数
	let _this = this;
	return function anonymous(...args){
		// args,可能传递的事件对象
		_this.call(context,params.concat(args));
		}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值