原型链闭包相关

一.判断数据类型的方法

  1. typeof:[]、null、{}都会返回object;undefined返回undefined;function(){}返回function
    只能说对[]和null的判断不够精确
  2. 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

  1. constructor
判断基本类型和复杂类型,但是如果原型改编后就不靠谱
function Fn(){};
Fn.prototype=new Array();
var f=new Fn();
console.log(f.constructor===Fn);    // false
console.log(f.constructor===Array); // true
  1. Object.prototype.toString.call
    返回结果为[Object Function]等

二.原型链

三.科里化

  1. 函数科里化:讲接受多个参数的函数转化为接受单一参数的函数,并返回接收剩余参数并且返回结果的新函数
  2. 通用写法
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的参数

  1. 改进版
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值