以下源码都来自webkit:
var d=Date() 与 var d=new Date的区别
前者只是一个普通的函数调用,是通过JSValue.getCallData来执行的,而后者是创建一个对象是通过
JSValue.getConstructData来执行的
因此两者可能存在本质的区别,区别在于调用返回时callData.native.function指向何处
通过对javascript core的分析可知,前者只是返回一个string,而后者则是创建了一个date对象
前者对应代码:
static JSValuePtr callDate(ExecState* exec, JSObject*, JSValuePtr,
const ArgList&)
{
DBUG_ENTER();
time_t localTime = time(0);
tm localTM;
getLocalTime(&localTime, &localTM);
GregorianDateTime ts(localTM);
return jsNontrivialString(exec, formatDate(ts) + " " +
formatTime(ts, false));
}
CallType DateConstructor::getCallData(CallData& callData)
{
DBUG_ENTER();
callData.native.function = callDate;
return CallTypeHost;
}
后者对应的代码:
static JSObject* constructWithDateConstructor(ExecState* exec,
JSObject*, const ArgList& args)
{
DBUG_ENTER();
return constructDate(exec, args);
}
ConstructType DateConstructor::getConstructData(ConstructData&
constructData)
{
DBUG_ENTER();
constructData.native.function = constructWithDateConstructor;
return ConstructTypeHost;
}
同样可以分析出var a=Array()和var a=new Array()是相同的
static JSObject* constructWithArrayConstructor(ExecState* exec,
JSObject*, const ArgList& args)
{
DBUG_ENTER();
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.4.2
ConstructType ArrayConstructor::getConstructData(ConstructData&
constructData)
{
DBUG_ENTER();
constructData.native.function = constructWithArrayConstructor;
return ConstructTypeHost;
}
static JSValuePtr callArrayConstructor(ExecState* exec, JSObject*,
JSValuePtr, const ArgList& args)
{
DBUG_ENTER();
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.6.1
CallType ArrayConstructor::getCallData(CallData& callData)
{
DBUG_ENTER();
// equivalent to 'new Array(....)'
callData.native.function = callArrayConstructor;
return CallTypeHost;
}