以下源碼都來自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)
callData.native.function = callDate;
return CallTypeHost;
後者對應的代碼:
static JSObject* constructWithDateConstructor(ExecState* exec,
JSObject*, const ArgList& args)
return constructDate(exec, args);
ConstructType DateConstructor::getConstructData(ConstructData&
constructData)
constructData.native.function = constructWithDateConstructor;
return ConstructTypeHost;
同樣可以分析出var a=Array()和var a=new Array()是相同的
static JSObject* constructWithArrayConstructor(ExecState* exec,
return constructArrayWithSizeQuirk(exec, args);
// ECMA 15.4.2
ConstructType ArrayConstructor::getConstructData(ConstructData&
constructData.native.function = constructWithArrayConstructor;
static JSValuePtr callArrayConstructor(ExecState* exec, JSObject*,
JSValuePtr, const ArgList& args)
// ECMA 15.6.1
CallType ArrayConstructor::getCallData(CallData& callData)
// equivalent to 'new Array(....)'
callData.native.function = callArrayConstructor;