JavaScript中的"+ new"是什么意思? [英] What does the '+new' mean in JavaScript?

查看:64
本文介绍了JavaScript中的"+ new"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在功能now()中浏览jQuery源,我看到以下内容:

Looking through the jQuery source in the function now() I see the following:

function now(){
    return +new Date;
}

我从未见过像这样的加号运算符会先于新的运算符.它是做什么的?

I've never seen the plus operator prepended to the new operator like this. What does it do?

推荐答案

尼古拉斯(Nicolás)和布莱恩(Brian)是正确的,但是如果您对它的工作原理感到好奇,则+new Date();等效于(new Date()).valueOf();,因为一元+运算符获得其操作数的表达式,然后将其转换为 ToNumber .

Nicolás and Brian are right, but if you're curious about how it works, +new Date(); is equivalent to (new Date()).valueOf();, because the unary + operator gets the value of its operand expression, and then converts it ToNumber.

您可以在任何对象上添加valueOf方法,并使用一元+运算符返回对象的数字表示形式,例如:

You could add a valueOf method on any object and use the unary + operator to return a numeric representation of your object, e.g.:

var productX = {
  valueOf : function () {
    return 500; // some "meaningful" number
  }
};

var cost = +productX; // 500

这篇关于JavaScript中的"+ new"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆