likes
comments
collection
share

Object.prototype.toString()

作者站长头像
站长
· 阅读数 265

1、对象上存在一个toString()方法,默认情况下,toString()方法被每个Object对象继承。如果此方法在自定义对象中未被覆盖,toString()返回[object type],其中type是对象的类型。

const str = new Object();
console.log(str.toString()); // [object Object]

2、使用toString()通过toString()来获取对象的类型。每个对象要通过Object.prototype.toString()获取对象类型,就需要通过 Function.prototype.call() 或者 Function.prototype.apply()来调用.

const { toString } = Object.prototype;

console.log(toString.call(new Date())); // [object Date]
console.log(toString.call(new String())); // [object String]