类型
2024年04月09日
一、Object.prototype.toString()
const obj1 = { name: 'obj1' };
const obj2 = { name: 'obj2' };
console.log(Object.prototype.toString.call(obj1)); // [object Object]
console.log(Object.prototype.toString.call(obj2)); // [object Object]
二、Object.prototype.toString() 和 Symbol.toStringTag()
Object.prototype.toString() 搭配 Symbol.toStringTag() 可以精准的判断对象具体类型
const obj1s = { name: 'obj1s' };
Object.defineProperty(obj1s, Symbol.toStringTag, {
value: 'obj1s',
});
const obj2s = { name: 'obj2s' };
Object.defineProperty(obj2s, Symbol.toStringTag, {
value: 'obj2s',
});
console.log(Object.prototype.toString.call(obj1s)); // [object obj1s]
console.log(Object.prototype.toString.call(obj2s)); // [object obj2s]