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;
複製代碼