Javascript中的运算符

所以我注意到了结果

(new Date())

是一个Date对象;在这种情况下

Date {Thu Dec 04 2014 22:43:07 GMT+0200 (SAST)}

但如果我输入

+(new Date())

我得到一个int值;

1417725787989

这是怎么做到的?

我有一个名为’Duration’的函数,当这样使用时:

new Duration(352510921)

返回一个如下所示的实例:

{ days:5, hours:3, mins:55, secs:10, ms:921 }

那么如何使用运算符来获取Duration实例的int值?

var dur = new Duration(352510921);
console.log(+dur) // prints int value 352510921
一元运算符将实例转换为Number,就像调用Number()函数将变量转换为Number一样.

如果您想覆盖特定实例的转换方式,则需要覆盖该实例的valueOf属性:

var a = {
    valueOf: function () {
        return 5;
    }
};
console.log(a); //Object { valueOf: function () {...} }
console.log(+a); //5

ES5 standard

11.4.6 Unary + Operator # Ⓣ Ⓡ Ⓖ

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return 07001(07002(expr)).

然后,对象上的ToNumber将生成带有提示号的ToPrimitive.然后ToPrimitive将调用[[DefaultValue]]内部方法,该方法指出:

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:

  1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument “valueOf”.
  2. If IsCallable(valueOf) is true then,
    1. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
    2. If val is a primitive value, return val.
  3. Let toString be the result of calling the [[Get]] internal method of object O with argument “toString”.
  4. If IsCallable(toString) is true then,
    1. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
    2. If str is a primitive value, return str.
  5. Throw a TypeError exception.
相关文章
相关标签/搜索