These are the global objects that are set up automatically by the SpiderMonkey js
command-line interpreter when you start the program.
Note: this list overlaps with "Built-in functions" in Introduction to the JavaScript shell and is probably not complete. See js/src/shell/js.cpp
(around shell_functions
) for more.
This page lists variables and functions available on SpiderMonkey 53. There may be some difference between each versions. You can get the list of functions by help()
function in js shell.
scriptArgs
scriptPath
console
log
stdout
. This function is an alias of the print()
function.timesAccessed
version([number])
options([option ...])
load(['foo.js' ...])
loadRelativeToScript(['foo.js' ...])
evaluate(code[, options])
options
is an optional object that may have these properties:
isRunOnce
isRunOnce
compiler option (default: false
)noScriptRval
false
)fileName
lineNumber
columnNumber
global
newContext
true
, create and use a new cx
(default: false
)catchTermination
true
, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated'
element
v
, convert v
to an object o
and mark the source as being attached to the DOM element o
. If the property is omitted or v
is null
, don't attribute the source to any DOM element.elementAttributeName
undefined
, the name of property of element
that holds this code. This is what Debugger.Source.prototype.elementAttributeName
returns.sourceMapURL
v
, convert v
to a string, and provide that as the code's source map URL. If omitted, attach no source map URL to the code (although the code may provide one itself, via a //#sourceMappingURL
comment).sourceIsLazy
true
, indicates that, after compilation, script source should not be cached by the JS engine and should be lazily loaded from the embedding as-needed.loadBytecode
true
, and if the source is a CacheEntryObject
, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual.saveBytecode
true
, and if the source is a CacheEntryObject
, the bytecode would be encoded and saved into the cache entry after the script execution.assertEqBytecode
true
, and if both loadBytecode
and saveBytecode
are true
, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ.run('foo.js')
read('bar.js')
readline()
stdin
.readlineBuf([ buf ])
readline()
on the specified string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line.print([exp ...])
stdout
.printErr([exp ...])
stderr
.putstr([exp])
dateNow()
help([name ...])
quit()
assertEq(actual, expected[, msg])
+0
or both -0
, both NaN
, or non-zero and ===
).startTimingMutator()
stopTimingMutator()
throwError()
JS_ReportError
.intern(str)
str
in the atom table.getslx(obj)
evalcx(s[, o])
s
in optional sandbox object o
. if (s == '' && !o)
return new o
with eager standard classes, if (s == 'lazy' && !o)
return new o
with lazy standard classesevalInWorker(str)
str
in a separate thread with its own runtime.getSharedArrayBuffer()
SharedArrayBuffer
object from the cross-worker mailbox. The object retrieved may not be identical to the object that was installed, but it references the same shared memory. getSharedArrayBuffer
performs an ordering memory barrier.setSharedArrayBuffer()
SharedArrayBuffer
object in the cross-worker mailbox. setSharedArrayBuffer
performs an ordering memory barrier.shapeOf(obj)
obj
(an implementation detail).groupOf(obj)
obj
(an implementation detail).unwrappedObjectsHaveSameShape(obj1, obj2)
true
iff obj1
and obj2
have the same shape, false
otherwise. Both objects are unwrapped first, so this can be used on objects from different globals.sleep(dt)
dt
seconds.compile(code)
parseModule(code)
Module
object.setModuleResolveHook(function(module, specifier) {})
HostResolveImportedModule
hook to function
. This hook is used to look up a previously loaded module object. It should be implemented by the module loader.getModuleLoadPath()
--module-load-path
argument passed to the shell. Used by the module loader.parse(code)
syntaxParse(code)
offThreadCompileScript(code[, options])
code
on a helper thread. To wait for the compilation to finish and run the code, call runOffThreadScript
. If present, options
may have properties saying how the code should be compiled:
noScriptRval
false
)fileName
lineNumber
columnNumber
element
v
, convert v
to an object o
and mark the source as being attached to the DOM element o
. If the property is omitted or v
is null
, don't attribute the source to any DOM element.elementAttributeName
undefined
, the name of property of element
that holds this code. This is what Debugger.Source.prototype.elementAttributeName
returns.runOffThreadScript()
offThreadCompileModule(code)
code
on a helper thread. To wait for the compilation to finish and get the module object, call finishOffThreadModule
.finishOffThreadModule()
timeout([seconds], [func])
setInterruptCallback
.interruptIf(cond)
true
. If a callback function is set via timeout
or setInterruptCallback
, it will be called. No-op otherwise.invokeInterruptCallback(fun)
timeout
or setInterruptCallback
, it will be called. Before returning, fun is called with the return value of the interrupt handler.setInterruptCallback(func)
func
as the interrupt callback function. Calling this function will replace any callback set by timeout
.enableLastWarning()
disableLastWarning()
getLastWarning()
clearLastWarning()
elapsed()
decompileFunction(func)
decompileThis()
thisFilename()
newGlobal([options])
sameZoneAs
invisibleToDebugger
false
)principal
0
subsumes nothing, while a principals of ~0
subsumes all other principals. The absence of a principal is treated as if its bits were 0xffff
, for subsumption purposes. If this property is omitted, supply no principal.createMappedArrayBuffer(filename, [offset, [size]])
addPromiseReactions(promise, onResolve, onReject)
JS::AddPromiseReactions
JSAPI function with the given arguments.getMaxArgs()
objectEmulatingUndefined()
obj
for which typeof obj === "undefined"
, obj == null
and obj == undefined
(and vice versa for !=
), and ToBoolean(obj) === false
.isCachingEnabled()
setCachingEnabled(b)
cacheEntry(code)
evaluate
function by using it in place of the source, and by setting saveBytecode
and loadBytecode
options.printProfilerEvents()
stderr
. Callback is only registered if profiling is enabled.enableSingleStepProfiling()
disableSingleStepProfiling()
enableSingleStepProfiling
.enableSPSProfiling()
enableSPSProfilingWithSlowAssertions()
disableSPSProfiling()
isLatin1(s)
stackPointerInfo()
int32
value which corresponds to the offset of the latest stack pointer, such that one can take the differences of 2 to estimate a frame-size.entryPoints(params)
params
, and return an array of objects describing which JavaScript entry points were invoked as a result. params
is an object whose properties indicate what operation to perform. Here are the recognized groups of properties:
{ function }
params.function
with no arguments.{ object, property }
params.property
of params.object
.{ ToString }
JS::ToString
to params.toString
.{ ToNumber }
JS::ToNumber
to params.toNumber
.{ eval }
JS::Evaluate
to params.eval
.'eval:FILENAME'
if the code was invoked by eval
or something similar.drainJobQueue()
setPromiseRejectionTrackerCallback()
disassemble([fun/code])
-r
-l
-S
dis([fun/code])
disfile('foo.js')
dissrc([fun/code])
notes([fun])
stackDump(showArgs, showLocals, showThisProps)
DumpJSStack()
function in the browser.arrayInfo(a1, a2, ...)
addIntlExtras(obj)
Intl
itself). The added functions and their behavior are experimental: don't depend upon them unless you're willing to update your code if these experimental APIs change underneath you.--fuzzing-safe
is not specifiedclone(fun[, scope])
getSelfHostedValue()
line2pc([fun,] line)
pc2line(fun[, pc])
nestedShell(shellArgs...)
nestedShell
. argv[0]
of the nested shell will be argv[0]
of the current shell (which is assumed to be the actual path to the shell. arguments[0]
(of the call to nestedShell
) will be argv[1]
, arguments[1]
will be argv[2]
, etc.assertFloat32(value, isFloat32)
value
has (resp. hasn't) the MIRType::Float32
if isFloat32
is true
(resp. false
).assertRecoveredOnBailout(var)
RecoveredOnBailout
flag.withSourceHook(hook, fun)
CompileOptions::LAZY_SOURCE
) to hook
; call fun
with no arguments; and then restore the runtime's original hook. Return or throw whatever fun
did. hook
gets passed the requested code's URL, and should return a string.
Notes:
fun
is not careful, hook
could be asked to retrieve the source code for compilations that occurred long before it was set, and that it knows nothing about. The reverse applies as well: the original hook, that we reinstate after the call to fun
completes, might be asked for the source code of compilations that fun
performed, and which, presumably, only hook
knows how to find.
wrapWithProto(obj)
trackedOpts(fun)
fun
, if any. If fun
is not a scripted function or has not been compiled by Ion, null
is returned.dumpScopeChain(obj)
crash([message])
MOZ_CRASH
.setARMHwCapFlags("flag1,flag2 flag3")
help
as the flag's namewasmLoop(filename, imports)
wasmEval
function together with the specified imports object.Testing functions are available also on Firefox via Components.utils.getJSTestingFunctions()
gc([obj] | 'zone' [, 'shrinking'])
zone
is given, GC any zones that were scheduled for GC via schedulegc. If shrinking
is passed as the optional second argument, perform a shrinking GC rather than a normal GC.minorgc([aboutToOverflow])
aboutToOverflow
is true, marks the store buffer as about-to-overflow before collecting.gcparam(name [, value])
JS_[GS]etGCParameter
. The name is one of:
relazifyFunctions(...)
gc()
.getBuildConfiguration()
hasChild(parent, child)
true
if child
is a child of parent
, as determined by a call to TraceChildren
setSavedStacksRNGState(seed)
SavedStacks
' RNG state.getSavedFrameCount()
SavedFrame
instances stored in this compartment's SavedStacks
cache.saveStack([maxDepth [, compartment]])
maxDepth
is given, capture at most maxDepth
number of frames. If compartment
is given, allocate the js::SavedFrame
instances with the given object's compartment.saveStack(object [, shouldIgnoreSelfHosted = true]])
shouldIgnoreSelfHosted
is given, control whether self-hosted frames are considered when checking principals.callFunctionFromNativeFrame(function)
function
with a (C++-)native frame on stack. Required for testing that SaveStack
properly handles native frames.callFunctionWithAsyncStack(function, stack, asyncCause)
function
, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws. The function is called with no arguments, and this
is undefined
. The specified asyncCause
is attached to the provided stack frame.enableTrackAllocations()
disableTrackAllocations()
makeFinalizeObserver()
finalizeCount
function.finalizeCount()
makeFinalizeObserver
is finalized.resetFinalizeCount()
finalizeCount()
.gcPreserveCode()
startgc([n [, 'shrinking']])
n
objects. If shrinking
is passesd as the optional second argument, perform a shrinking GC rather than a normal GC.gcslice([n])
n
objects.abortgc()
fullcompartmentchecks(true|false)
true
, check for compartment mismatches before every GC.nondeterministicGetWeakMapKeys(weakmap)
internalConst(name)
InternalConst
source for the list of constant names.isProxy(obj)
true
, obj
is a proxy of some sortdumpHeap(['collectNurseryBeforeDump'], [filename])
stdout
. If collectNurseryBeforeDump
is specified, a minor GC is performed first, otherwise objects in the nursery are ignored.terminate()
readSPSProfilingStack()
ProfilingFrameIterator
.enableOsiPointRegisterChecks()
OsiPoint
.displayName(fn)
name
property on the function.isAsmJSCompilationAvailable
isSimdAvailable
true
if SIMD extensions are supported on this platform.getCompilerOptions()
isAsmJSModule(fn)
"use asm"
that has been validated according to the asm.js spec.isAsmJSModuleLoadedFromCache(fn)
isAsmJSFunction(fn)
wasmIsSupported()
wasmTextToBinary(str)
wasmBinaryToText(bin)
wasmExtractCode(module)
isLazyFunction(fun)
True
if fun is a lazy JSFunction
.isRelazifiableFunction(fun)
Ture
if fun is a JSFunction
with a relazifiable JSScript
.enableShellAllocationMetadataBuilder()
ShellAllocationMetadataBuilder
to supply metadata for all newly created objects.getAllocationMetadata(obj)
bailout()
bailAfter(number)
inJit()
true
when called within (jit-)compiled code. When jit compilation is disabled this function returns an error string. This function returns false
in all other cases. Depending on truthiness, you should continue to wait for compilation to happen or stop execution.inIon()
true
when called within ion. When ion is disabled or when compilation is abnormally slow to start, this function returns an error string. Otherwise, this function returns false
. This behaviour ensures that a falsy value means that we are not in ion, but expect a compilation to occur in the future. Conversely, a truthy value means that we are either in ion or that there is litle or no chance of ion ever compiling the current script.assertJitStackInvariants()
setCompilerOption(option, number)
setIonCheckGraphCoherency(bool)
serialize(data, [transferables, [policy]])
data
using JS_WriteStructuredClone
. Returns a structured clone buffer object. policy
must be an object. The following keys' string values will be used to determine whether the corresponding types may be serialized (value allow
, the default) or not (value deny
). If denied types are encountered a TypeError will be thrown during cloning. Valid keys: SharedArrayBuffer
.deserialize(clonebuffer)
detachArrayBuffer(buffer)
ArrayBuffer
object from its memory, i.e. as if it had been transferred to a WebWorker.helperThreadCount()
reportOutOfMemory()
throwOutOfMemory()
reportLargeAllocationFailure()
findPath(start, target)
start
to target
, or undefined
if target
is unreachable from start
. Each element of the array is either of the form: { node: {object or string}, edge: {string describing edge from node} }
, if the node is a JavaScript object or value; or of the form: { type: {string describing node}, edge: {string describing edge} }
, if the node is some internal thing that is not a proper JavaScript value (like a shape or a scope chain element). The destination of the i'th array element's edge is the node of the i+1'th array element; the destination of the last array element is implicitly target
.shortestPaths(start, targets, maxNumPaths)
targets
. The maximum number of paths in each of those arrays is bounded by maxNumPaths
. Each element in a path is of the form { predecessor, edge }
.sharedMemoryEnabled()
SharedArrayBuffer
and Atomics are enabledevalReturningScope(scriptStr, [global])
global
is present, clone the script to global
before executing.cloneAndExecuteScript(source, global)
source
in the current compartment, clone it into global
's compartment, and run it there.backtrace()
getBacktrace([options])
options.args
- show arguments to each function options.locals
- show local variables in each frame options.thisprops
- show the properties of the this
object of each framebyteSize(value)
value
, or undefined
if value is not allocated in memory.byteSizeOfScript(f)
f
's JSScript.setImmutablePrototype(obj)
[[Prototype]]
immutable, such that subsequent attempts to change it will fail. Return true
if obj's [[Prototype]]
was successfully made immutable (or if it already was immutable), false
otherwise. Throws in case of internal error, or if the operation doesn't even make sense (for example, because the object is a revoked proxy).setLazyParsingDisabled(bool)
setDiscardSource(bool)
getConstructorName(object)
new Ctor
, return the constructor's display name. Otherwise, return null
.allocationMarker([options])
[[Class]]
name is AllocationMarker
. Such objects are allocated only by calls to this function, never implicitly by the system, making them suitable for use in allocation tooling tests. Takes an optional options object which may contain the following properties: * nursery: bool, whether to allocate the object in the nurserysetGCCallback({action:"...", options...})
minorGC
majorGC
depth
getLcovInfo(global)
getModuleEnvironmentNames(module)
getModuleEnvironmentValue(module, name)
enableForEach()
disableForEach()
settlePromiseNow(promise)
promise
immediately. This just marks the promise as resolved with a value of undefined
and causes the firing of any onPromiseSettled
hooks set on Debugger
instances that are observing the given promise's global as a debuggee.getWaitForAllPromise(densePromisesArray)
GetWaitForAllPromise
JSAPI function and returns the result Promise.resolvePromise(promise, resolution)
Promise
by calling the JSAPI function JS::ResolvePromise
.rejectPromise(promise, reason)
Promise
by calling the JSAPI function JS::RejectPromise
.makeFakePromise()
[[Class]]
name is 'Promise'
and call JS::dbg::onNewPromise
on it before returning it. It doesn't actually have any of the other behavior associated with promises.settleFakePromise(promise)
promise
created by makeFakePromise()
. This doesn't have any observable effects outside of firing any onPromiseSettled
hooks set on Debugger
instances that are observing the given promise's global as a debuggee.gczeal(level, [N])
"2;4"
will activate both modes 2 and 4. Modes can be specified by name or number.
Values:
0: (None)
1: (Poke)
2: (Alloc)
N
allocations (default: 100)3: (FrameGC)
4: (VerifierPre)
5: (FrameVerifierPre)
6: (StackRooting)
7: (GenerationalGC)
N
nursery allocations8: (IncrementalRootsThenFinish)
9: (IncrementalMarkAllThenFinish)
10: (IncrementalMultipleSlices)
11: (IncrementalMarkingValidator)
12: (ElementsBarrier)
13: (CheckHashTablesOnMinorGC)
14: (Compact)
15: (CheckHeapAfterGC)
16: (CheckNursery)
schedulegc([num | obj])
selectforgc(obj1, obj2, ...)
verifyprebarriers()
verifypostbarriers()
gcstate()
deterministicgc(true|false)
true
, only allow determinstic GCs to run.startTraceLogger()
TLOPTIONS=disableMainThread
stopTraceLogger()
objectAddress(obj)
sharedAddress(obj)
SharedArrayBuffer
.dumpObject()
dumpStringRepresentation(str)
str
is represented.setRNGState(seed0, seed1)
oomThreadTypes()
oomAfterAllocations()
and oomAtAllocation()
.oomAfterAllocations(count [,threadType])
count
js_malloc
memory allocations, fail every following allocation (return nullptr
). The optional thread type limits the effect to the specified type of helper thread.oomAtAllocation(count [,threadType])
count
js_malloc
memory allocations, fail the next allocation (return nullptr
). The optional thread type limits the effect to the specified type of helper thread.resetOOMFailure()
oomAfterAllocations()
or oomAtAllocation()
and return whether any allocation had been caused to fail.oomTest(function, [expectExceptionOnFailure = true])
--fuzzing-safe
is specified.--fuzzing-safe
is not specified andparseRegExp(pattern[, flags[, match_only])
RegExp
pattern and returns a tree, potentially throwing.disRegExp(regexp[, match_only[, input]])
RegExp
bytecode.