我是新来的JS,我被简单的(?)课堂问题
我所需要做的就是将一些字符串放入代码中,以使断言表达式有效。
class Rec {
constructor() {
let a = 0;
this['put here'] = () => a+++a;
}
}
let inst = new Rec();
console.assert(
inst == 1 && inst == 3 && inst == 5
);注意到类有着无尽的价值链,比如
__proto__:
constructor:
prototype:
constructor:
prototype:
...etc因此,我尝试使用__proto__,但得到了一个Function.prototype.toString requires that 'this' be a Function错误。
发布于 2019-08-20 15:04:07
您可以使用valueOf或toString
class Rec {
constructor() {
let a = 0;
this['valueOf'] = () => a+++a;
}
}
let inst = new Rec();
console.log(
inst == 1 && inst == 3 && inst == 5
);
这是因为一个对象(inst)和一个数字之间的抽象相等比较。
从规格说明,
作为比较,x == y
对象的ToPrimitive调用valueOf方法(如果hint是Number )。
如果展开表达式,则如下所示:a++ + a。每次比较inst时,都会调用valueOf方法。并返回a++和a之和。
https://stackoverflow.com/questions/57576461
复制相似问题