且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改包装的原始数据类型的值

更新时间:2023-02-26 22:31:46

内置对象包装器(使用 BooleanNumberStringDate 构造函数)将原始包装值存储在名为 [[PrimitiveValue]] 的内部属性中,该属性无法更改,但是...

Built-in object wrappers (created with the Boolean, Number, String and Date constuctors) store the primitive wrapped value in an internal property named [[PrimitiveValue]], which cannot be changed, but...

您可以覆盖 test 对象的 valueOf 方法:

You can override the valueOf method of your test object:

var test = new Boolean(0);
test.prop = "OK!"
// override valueOf:
test.valueOf = function () { return true; };

if (test == true) { // using the equals operator explicitly for type conversion
  alert(test.prop); //"OK!"
}

它会起作用,因为 valueOf 方法是由 equals 运算符触发的类型转换机制在内部使用的.

It will work since the valueOf method is used internally by the type-conversion mechanisms triggered by the equals operator.

当其中一个操作数是布尔值时,两者都在末尾转换为数字.

When one of the operands is a Boolean value, both are converted at the end to Number.

如果我们不使用等号运算符(例如 if (test) { ... }),因为 test 是一个对象,当直接转换为 Boolean,它总是会产生 true.

If we don't use the equals operator (e.g. if (test) { ... }), since test is an object, when converted directly to Boolean, it will always yield true.

任何转换为​​布尔值的对象都会产生 true 值,唯一可以产生 false 结果的值是falsey"值(nullundefined0NaN,一个空字符串,当然还有false值),其他任何事情都会产生 true.

Any object converted to Boolean will produce the true value, the only values that can produce a false result, are the "falsey" values (null, undefined, 0, NaN, an empty string, and of course the false value), anything else will produce true.

更多信息: