Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用Symbol.toStringTag后,type函数会判断错误 #6

Open
wyjie opened this issue Mar 12, 2021 · 3 comments
Open

使用Symbol.toStringTag后,type函数会判断错误 #6

wyjie opened this issue Mar 12, 2021 · 3 comments
Labels
bug Something isn't working

Comments

@wyjie
Copy link

wyjie commented Mar 12, 2021

const object1 = {};
object1[Symbol.toStringTag] = 'Array';
console.log(type(object1));  // Array

是否可以去掉47行的if判断,直接使用对象的constructor

if(x.constructor == Object){
        return clsLow;
    }
@yanhaijing yanhaijing added the bug Something isn't working label Mar 12, 2021
@yanhaijing
Copy link
Member

yanhaijing commented Nov 28, 2021

const object1 = {};
object1[Symbol.toStringTag] = 'Array';
console.log(type(object1));  // Array

这个期望object1的返回值是 'object' 而不是 'Array'吗?如果自定义了Symbol.toStringTag,感觉返回Symbol.toStringTag是合理的吧?

@wyjie
Copy link
Author

wyjie commented Dec 23, 2021

const object1 = {};
object1[Symbol.toStringTag] = 'Array';
console.log(type(object1));  // Array

这个期望object1的返回值是 'object' 而不是 'Array'吗?如果自定义了Symbol.toStringTag,感觉返回Symbol.toStringTag是合理的吧?

好像也有道理

@yanhaijing
Copy link
Member

yanhaijing commented Dec 23, 2021

Symbol.toStringTag 似乎就是为了修复,自定义的类实例,type都是object的问题吧

原来的场景

function A() {}

const a = new A
Object.prototype.toString.call(a) // '[object Object]'

Symbol.toStringTag改进后的情况

function A() {
  this[Symbol.toStringTag] = 'A' // 注意这里的区别
}

const a = new A
Object.prototype.toString.call(a) // '[object A]'

有了Symbol.toStringTag内部类可以区分开 自定义对象和原生对象了,没有Symbol.toStringTag,只能去constructor上面判断才可以(目前type库就是从这里拿的)

function A() {}

const a = new A
Object.prototype.toString.call(a) // '[object Object]' 这里无法区分

console.log(a.constructor.name) // 'A'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants