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

实现 (5).add(3).minus(2) 功能(Number里的this和this.value) #42

Open
lovelmh13 opened this issue Feb 23, 2020 · 0 comments
Open

Comments

@lovelmh13
Copy link
Owner

lovelmh13 commented Feb 23, 2020

原题

最简单的,不加任何其他检验,默认传递的就是数字,不考虑精度丢失的问题:

Number.prototype.add = function (num) {
	return this.valueOf() + num;
}
Number.prototype.minus = function (num) {
	return this.valueOf() - num;
}
console.log((5).add(3).minus(2));

这里面为什么要写this.value,而不直接写this呢?

this打印出来的是Number {5},它里面包含__proto__: Number[[PrimitiveValue]]: 5
如果用this.value则会直接打印出来 5

[[PrimitiveValue]]Number类型对象内部的原始值,是经过类型转换后获得的数字值

但是,这里还有个疑问:

Number.prototype.add = function (num) {
	console.log(this)
}
(5).add()

这样,this 打印出来是window,为什么不会指向5呢? 如果包上console.log变成console.log((5).add(3);就可以指向5

搞不清楚这个问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant