-
Notifications
You must be signed in to change notification settings - Fork 457
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
下面代码a在什么情况中打印出1? #23
Comments
1.在类型转换的时候,我们知道了对象如何转换成原始数据类型。如果部署了 [Symbol.toPrimitive],那么返回的就是Symbol.toPrimitive的返回值。当然,我们也可以把此函数部署在valueOf或者是toString接口上,效果相同。 //利用闭包延长作用域的特性
let a = {
[Symbol.toPrimitive]: (function() {
let i = 1;
return function() {
return i++;
}
})()
} (1). 比较 a == 1 时,会调用 [Symbol.toPrimitive],此时 i 是 1,相等。 2.利用Object.definePropert在window/global上定义a属性,获取a属性时,会调用get. let val = 1;
Object.defineProperty(window, 'a', {
get: function() {
return val++;
}
}); 3.利用数组的特性。 var a = [1,2,3];
a.join = a.shift; 数组的 因此,我们可以重新 join 方法。返回第一个元素,并将其删除。 |
第一反应是Generator函数,后来写了下发现并不简洁0.0 |
可以使用js的getter属性。每次getter就让a++,初始化a = 1 |
这在你不知道js里面有介绍,建议作者介绍知识点的时候给大家提供一些来源,这样才是知识面 |
第一眼看到还以为是脑筋急转弯。。 |
The text was updated successfully, but these errors were encountered: