new的过程前端
/**
*
* @param {<function>} fn 构造函数
* @param {...any} args 构造函数能够接受参数
*/
function myNew (fn, ...args) {
var obj = {};
obj.__proto__ = fn.prototype;
var ret = fn.call(obj, ...args);
return typeof ret === 'function' || (typeof ret === 'object' && ret !== null) ? ret : obj;
}
New的过程:
1. 建立一个空对象,
2. 对象的__proto__链接到构造函数的prototype
3. 执行构造函数, this指向空对象
4. 处理边缘状况,返回值
var Person = function (name, age) {
this.name = name;
this.age = age;
};
myNew(Person, 'biubiu', 10) // {name: 'biubiu', age: 10};
复制代码
instanceofvue
/**
*
* @param {*} left
* @param {*} right
*/
instanceof : 意思是left的原型链上是否能找到right的prototype属性, 用来检测类型是不建议使用的, 不严谨
[] instanceof Array => true;
[] instanceof Object => true;
function myInstanceof (left, right) {
var isFind = false;
var proto = left.__proto__;
var prototype = right.prototype;
while (proto !== null) {
if (proto !== prototype) {
proto = proto.__proto__;
} else {
isFind = true;
break;
}
}
return isFind;
}
关于使用es5严格检测数据类型
var type = type => data => type === Object.prototype.toString.call(data).slice(8, -1);
var util = {
isArray: type('Array'),
isNumber: type('Number'),
isString: type('String'),
isObject: type('Object'),
isPromise: type('Promise'),
isSymbol: type('Symbol'),
isNull: type('Null'),
isUndefined: type('Undefined'),
isFunction: type('Function')
}
util.isFunction(Function) // true;
复制代码