美文网首页让前端飞Web前端之路
[].slice.call(obj)和Object.protot

[].slice.call(obj)和Object.protot

作者: 裸泳的小熊 | 来源:发表于2020-04-26 10:07 被阅读0次

任何函数都有call这个方法,call属于Function.prototype的一个方法,所以每个function实例都有call属性。

一、[].slice.call(obj)

slice 这个方法在不接受任何参数的时候会返回 this 本身
arguments 是属于函数内部的变量,其值是函数参数列表,一个类数组对象,是具有长度属性的,却并不是数组,不具备slice()这个方法,那就意味着 arguments.slice() 行不通

[].slice.call(arguments)或者Array.prototype.slice.call(arguments)方法可以让arguments拥有数组的所有方法。call方法的含义:改变this指向。obj1.(method).call(obj2,argument1,argument2)
如上,call的作用就是把obj1的方法放到obj2上使用,后面的argument1..这些做为参数传入。

ES6中的Array.from(argument)和[...argument]可以将类数组转化成数组。

二、Object.prototype.toString.call()

在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number、string、undefined、boolean、object。
对于null、array、function、object来说,使用typeof都会统一返回object字符串。
要想区分对象、数组、函数、单纯使用typeof是不行的。在JS中,可以通过Object.prototype.toString方法,判断某个对象之属于哪种内置类型。
分为null、string、boolean、number、undefined、array、function、object、date、math。

  1. 判断基本类型
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(“abc”);// "[object String]"
Object.prototype.toString.call(123);// "[object Number]"
Object.prototype.toString.call(true);// "[object Boolean]"
  1. 判断原生引用类型
**函数类型**
Function fn(){
  console.log(“test”);
}
Object.prototype.toString.call(fn); // "[object Function]"
**日期类型**
var date = new Date();
Object.prototype.toString.call(date); // "[object Date]"
**数组类型**
var arr = [1,2,3];
Object.prototype.toString.call(arr); // "[object Array]"
**正则表达式**
var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg); // "[object RegExp]"
**自定义类型**
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Person.prototype.toString.call(person); // "[object Object]"
很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
console.log(person instanceof Person); // true

相关文章

网友评论

    本文标题:[].slice.call(obj)和Object.protot

    本文链接:https://www.haomeiwen.com/subject/vsarwhtx.html