一.判断数据类型的方法
- typeof:[]、null、{}都会返回object;undefined返回undefined;function(){}返回function
只能说对[]和null的判断不够精确 - instanceof:用来测试一个对象object在其原型链中是否存在一个构造函数constructor的prototype属性
只能判断对象,不能判断基本类型
格式:object instanceof constructor;右侧为检测的类型
(1)简单类型(String、Number、Boolean、Undefined、Null、Symbol):最好不要;只有通过new声明的才能够检测出true,new会封装为对象
let num = 2;
console.log(num instanceof Number); // false
let num = Number(2);
console.log(num instanceof Number); // false
let num = new Number(2);
console.log(num instanceof Number); // true
(2)null和undefined不能这么判断,会报错;浏览器不认识null和undefined,认为不是构造器
Right-hand side of 'instanceof' is not an object
(3)复杂数据可以直接判断
复杂类型:Array,Object;
其他类型:Function、RegExp、Date
注意:
let num = 1;
console.log(num.proto === Number.prototype) ;// true
console.log(num instanceof Number) // false
num = new Number(1)
console.log(num.proto === Number.prototype) // true
console.log(num instanceof Number) // true
console.log(num.proto === (new Number(1)).proto) // true
- constructor
判断基本类型和复杂类型,但是如果原型改编后就不靠谱
function Fn(){};
Fn.prototype=new Array();
var f=new Fn();
console.log(f.constructor===Fn); // false
console.log(f.constructor===Array); // true
- Object.prototype.toString.call
返回结果为[Object Function]等
二.原型链
三.科里化
- 函数科里化:讲接受多个参数的函数转化为接受单一参数的函数,并返回接收剩余参数并且返回结果的新函数
- 通用写法
function multiFn(a,b,c){
return a * b * c;
}
function curry(fn) {
var args = Array.prototype.slice.call(arguments,1); //其实就是初始化一个[];1是去掉第一项
return function () {
var newArgs = args.concat(Array.prototype.slice.call(arguments)); //[3,5,3]
return fn.apply(this,newArgs);
}
}
var multi = curry(multiFn);
console.log(multi(3,5,3))
缺点:不能接受小于长度为3的参数
- 改进版
function curry(fn,args){
var args = args || []; //重要
var length = fn.length;
return function () {
var newArgs = args.concat(Array.prototype.slice.call(arguments));
if (newArgs.length < length){
return curry.call(this,fn,newArgs);
} else {
return fn.apply(this,newArgs);
}
}
}
var multi = curry(multiFn);
console.log(multi(2)(3)(4));
console.log(multi(2,3)(4));
缺点:参数总长度固定
4. 优化
function curry() {
var args = Array.prototype.slice.call(arguments);
var fn = function () {
var newArgs = args.concat(Array.prototype.slice.call(arguments));
return curry.apply(this,newArgs);
}
fn.toString = function () {
return args.reduce(function (a,b) {
return a * b;
})
}
return fn;
}
console.log(curry(3,4)(6)(7)(63).toString())
参考文章:https://juejin.im/post/5b8350246fb9a019c372d26d