Search completed in 1.51 seconds.
Object.prototype.toString() - JavaScript
The
toString() method returns a string representing the object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj.
toString() Return value A string representing the object. Description Every object has a
toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the
toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object,
toString() returns "[object type]", where type is the object type. The following code illustrat...
... when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the
toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object,
toString() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object(); o.
toString(); // returns [object Object] Note: Starting in JavaScript 1.8.5,
toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. ...
...n in a custom object,
toString() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object(); o.
toString(); // returns [object Object] Note: Starting in JavaScript 1.8.5,
toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. See Using
toString() to detect object class. Parameters For Numbers and BigInts
toString() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. By using radix you can also convert base 10 numbers (like 1,2,3,4,5,.........) to another base numbers, in example below we are converting base 10 number to a base 2 (binary) number let baseTenInt = 10; console.log(baseTenInt.toStr...
...And 14 more matches
nsAutoString
Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
... Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
... Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
...And 8 more matches
nsCAutoString
Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
... Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
... Class Declaration nsTAu
toString_CharT Subclass of nsTString_CharT that adds support for stack-based string allocation. It is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
...And 8 more matches
Function.prototype.toString() - JavaScript
The
toString() method returns a string representing the source code of the function. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax function.
toString() Return value A string representing the source code of the function. Description The Function object overrides the
toString method inherited from Object; it does not inherit Object.prototype.
toString. For user-defined Function objects, the
toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the
toString method automatically when a Function is to be represented as a text value, e.g. when ...
... the
toString method inherited from Object; it does not inherit Object.prototype.
toString. For user-defined Function objects, the
toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the
toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string. The
toString() method will throw a TypeError exception ("Function.prototype.
toString called on incompatible object"), if its this value object is not a Function object. ...
...text segment which was used to define the function. JavaScript calls the
toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string. The
toString() method will throw a TypeError exception ("Function.prototype.
toString called on incompatible object"), if its this value object is not a Function object. ...
...And 7 more matches
Symbol.toStringTag - JavaScript
The Symbol.
toStringTag well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the Object.prototype.
toString() method. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... creation of the default string description of an object. It is accessed internally by the Object.prototype.
toString() method. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ed in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...And 7 more matches
BigInt.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified BigInt object. The trailing "n" is not part of the string. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax bigIntObj.
toString([radix]) Parameters radixOptional Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified BigInt object. Exceptions RangeError If
toString() is given a radix less than 2 or greater than 36, a RangeError is thrown. ...
...yntax bigIntObj.
toString([radix]) Parameters radixOptional Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified BigInt object. Exceptions RangeError If
toString() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The BigInt object overrides the
toString() method of the Object object; it does not inherit Object.prototype.
toString(). For BigInt objects, the
toString() method returns a string representation of the object in the specified radix. The
toString() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radixes above 10, the letters of the alphabet indicate numerals greater tha...
...an 9. For example, for hexadecimal numbers (base 16) a through f are used. If the radix is not specified, the preferred radix is assumed to be 10. If the bigIntObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the bigIntObj preceded by a - sign, not the two's complement of the bigIntObj. ...
...And 6 more matches
Error.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified Error object. Syntax e.
toString() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.
toString() method inherited by all objects. ...
... The
toString() method returns a string representing the specified Error object. Syntax e.
toString() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.
toString() method inherited by all objects. ...
...= function() { 'use strict'; var obj = Object(this); if (obj !== this) { throw new TypeError(); } var name = this.name; name = (name === undefined) ? 'Error' : String(name); var msg = this.message; msg = (msg === undefined) ? ...
...And 6 more matches
RegExp.prototype.toString() - JavaScript
The
toString() method returns a string representing the regular expression. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax regexObj.
toString(); Return value A string representing the given object. Description The RegExp object overrides the
toString() method of the Object object; it does not inherit Object.prototype.
toString(). For RegExp objects, the
toString() method returns a string representation of the regular expression. ...
...thub.com/mdn/interactive-examples and send us a pull request. Syntax regexObj.
toString(); Return value A string representing the given object. Description The RegExp object overrides the
toString() method of the Object object; it does not inherit Object.prototype.
toString(). For RegExp objects, the
toString() method returns a string representation of the regular expression. ...
... given object. Description The RegExp object overrides the
toString() method of the Object object; it does not inherit Object.prototype.
toString(). For RegExp objects, the
toString() method returns a string representation of the regular expression. ...
...And 5 more matches
Date.prototype.toString() - JavaScript
"Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. ...
..."Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. ...
...a string representing the specified Date object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.
toString() Return value A string representing the given date. Description Date instances inherit their
toString() method from Date.prototype, not Object.prototype. Date.prototype.
toString() returns a string representation of the Date in the format specified in ECMA-262 which can be summarised as: Week day: 3 letter English week day name, e.g. "Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. "01" space Year: 4 digit year, e.g. "2018" space Hou...
...And 3 more matches
Number.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified Number object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax numObj.
toString([radix]) Parameters radix Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified Number object. Exceptions RangeError If
toString() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The Number object overrides the
toString() method of the Object object. (It does not inherit Object.prototype.
toString()). For Number object...
...cifying the base to use for representing numeric values. Return value A string representing the specified Number object. Exceptions RangeError If
toString() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The Number object overrides the
toString() method of the Object object. (It does not inherit Object.prototype.
toString()). For Number objects, the
toString() method returns a string representation of the object in the specified radix. The
toString() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used. If the radix is not specified, the pr...
...adix is not specified, the preferred radix is assumed to be 10. If the numObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the numObj preceded by a - sign, not the two's complement of the numObj. If the numObj is not a whole number, the 'dot' sign is used to separate the decimal places. ...
...And 3 more matches
HTMLHyperlinkElementUtils.toString() - Web APIs
The HTMLHyperlinkElementUtils.
toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
... The HTMLHyperlinkElementUtils.
toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
... The HTMLHyperlinkElementUtils.
toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
...And 2 more matches
Location: toString() - Web APIs
The
toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
... The
toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
... The
toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
...And 2 more matches
Intl.Locale.prototype.toString() - JavaScript
The Intl.Locale.prototype.
toString() returns the Locale's full locale identifier string. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax locale.
toString() Return value The locale's Unicode locale identifier string. Description The Locale object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. ...
...n value The locale's Unicode locale identifier string. Description The Locale object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. ...
...pt representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. Calling the
toString method on a Locale object will return the identifier string for that particular Locale. ...
...And 2 more matches
JS_ValueToString
Obsolete since JSAPI 28This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Convert a jsval to a JSString. Syntax JSString * JS_Value
ToString(JSContext *cx, jsval v); Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. Description JS_Value
ToString converts a specified JavaScript value, v, to a string. It implements the
ToString operator specified in ECMA 262-3 ?9.8. The result is like the JavaScript expression ""+v. If v is already a string, conversion succeeds. If v is true,...
...and the result is the string "true", "false", "null", or "undefined", accordingly. If v is a number, conversion succeeds, and the result is a string representation of that number as specified in ECMA 262-3 ?9.8.1. This might be "NaN", "Infinity", or "-Infinity". Otherwise the result is a decimal representation of the number, possibly using exponential notation. Otherwise v is an object. JS_Value
ToString uses the steps below to convert it to a string. If at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (This behavior is implemented by v's JSObjectOps.defaultValue method, so host objects can override it all.) If v.
toString() is a function, it is called. If that method returns a primitive value, the value is converted to a string as describ...
...above and conversion succeeds. Otherwise, the resulting object's JSClass.convert callback is called. For standard classes, this is JS_ConvertStub, which simply calls v.valueOf() if present. If the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds. ...
...is JS_ConvertStub, which simply calls v.valueOf() if present. If the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds. Otherwise conversion fails with a TypeError. On success, JS_Value
ToString returns a pointer to a string. On error or exception, it returns NULL. This happens, for example, if v is an object and v.
toString() throws an exception. The resulting JSString is subject to garbage collection. Protect it using a local root, an object property, or the JS_AddRoot function. See Also bug 933834 JS::
ToString ...
URL.toString() - Web APIs
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
toString - Archive of obsolete content
Summary converts an InstallVersion init object to a string. Method of InstallVersion object Syntax String version = InstallVersion.
toString ( initObj ); Parameters The
toString method has the following parameter: initObj initObj is an InstallVersion object whose init method has been called. Returns The major, minor, revision, and build numbers represented as a single string. The init() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
...on object whose init method has been called. Returns The major, minor, revision, and build numbers represented as a single string. ...
...er as a single string or as a series of parameters representing the version numbers of the installation. ...
XMLSerializer.serializeToString() - Web APIs
Return value A DOMString containing the XML representation of the specified DOM tree. Exceptions TypeError The specified rootNode is not a compatible node type. The root node must be either Node or Attr. InvalidStateError The tree could not be successfully serialized, probably due to issues with the content's compatibility with XML serialization. ...
... be either a Node or Attr object. The following types are also permitted as descendants of the root node, in addition to Node and Attr: DocumentType Document DocumentFragment Element Comment Text ProcessingInstruction Attr If any other type is encountered, a TypeError exception is thrown. Notes on the resulting XML There are some things worth noting about the XML output by serialize
ToString(): For XML serializations, Element and Attr nodes are always serialized with their namespaceURI intact. This may mean that a previously-specified prefix or default namespace may be dropped or altered. The resulting XML is compatible with the HTML parser. Elements in the HTML namespace that have no child nodes (thereby representing empty tags) are serialized with both begin and end tags ("<so...
...lting XML is compatible with the HTML parser. Elements in the HTML namespace that have no child nodes (thereby representing empty tags) are serialized with both begin and end tags ("<someelement></someelement>") instead of using the empty-element tag ("<someelement/>"). Specifications Specification Status Comment DOM Parsing and SerializationThe definition of 'serialize
ToString()' in that specification. Working Draft ...
Symbol.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified Symbol object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol().
toString() Return value A string representing the specified Symbol object. Description The Symbol object overrides the
toString method of the Object object; it does not inherit Object.prototype.
toString(). For Symbol objects, the
toString method returns a string representation of the object. ...
...ve-examples and send us a pull request. Syntax Symbol().
toString() Return value A string representing the specified Symbol object. Description The Symbol object overrides the
toString method of the Object object; it does not inherit Object.prototype.
toString(). For Symbol objects, the
toString method returns a string representation of the object. ...
...ject overrides the
toString method of the Object object; it does not inherit Object.prototype.
toString(). For Symbol objects, the
toString method returns a string representation of the object. No string concatenation While you can call
toString() on Symbols, you cannot use string concatenation with them: Symbol('foo') + 'bar' // TypeError: Can't convert symbol to string Examples Using
toString Symbol('desc').
toString() // "Symbol(desc)" // well-known symbols Symbol.iterator.
toString() // "Symbol(Symbol.iterator) // global symbols Symbol.for('foo').
toString() // "Symbol(foo)" Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.
toString' in that specification. ...
TypedArray.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified array and its elements. This method has the same algorithm as Array.prototype.
toString(). TypedArray is one of the typed array types here. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.
toString() Return value A string representing the elements of the typed array. Examples The TypedArray objects override the
toString method of Object. For TypedArray objects, the
toString method joins the array and returns one string containing each typed array element separated by commas. For example, the following code creates a typed array and us...
...nd us a pull request. Syntax typedarray.
toString() Return value A string representing the elements of the typed array. Examples The TypedArray objects override the
toString method of Object. For TypedArray objects, the
toString method joins the array and returns one string containing each typed array element separated by commas. For example, the following code creates a typed array and uses
toString to convert the array to a string. var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.
toString(); // "2,5,8,1,4" JavaScript calls the
toString method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. ...
... code creates a typed array and uses
toString to convert the array to a string. var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.
toString(); // "2,5,8,1,4" JavaScript calls the
toString method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. Compatibility If a browser doesn't support the TypedArray.prototype.
toString() method yet, JavaScript will call the
toString method of Object: var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.
toString(); // "[object Uint8Array]" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.
toString' in that specification. ...
JS::ToString
This article covers features introduced in SpiderMonkey 31 Convert any JavaScript value to a string. Syntax #include "js/Conversions.h" // as of SpiderMonkey 38; previously in jsapi.h JSString* JS::
ToString(JSContext *cx, JS::HandleValue v) Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. Description JS::
ToString returns a string representation of a JavaScript value. If v.isString() is true, it calls v.
toString(). Otherwise, it converts the value to string. On success, JS::
ToString returns a JSString instance. On error or exception, it returns nullptr. See Als...
...n a request on this JSContext. v JS::HandleValue The value to convert. Description JS::
ToString returns a string representation of a JavaScript value. If v.isString() is true, it calls v.
toString(). Otherwise, it converts the value to string. On success, JS::
ToString returns a JSString instance. ...
JS_VersionToString
Returns a string representation of a JSVersion value. Syntax const char * JS_Version
ToString(JSVersion version); Name Type Description version JSVersion Version value to convert. Description JS_Version
ToString attempts to convert the version to a const char * string representation. ...
... Returns a string representation of a JSVersion value. Syntax const char * JS_Version
ToString(JSVersion version); Name Type Description version JSVersion Version value to convert. Description JS_Version
ToString attempts to convert the version to a const char * string representation. ...
Range.toString() - Web APIs
The Range.
toString() method is a stringifier returning the text of the Range. Alerting the contents of a Range makes an implicit
toString() call, so comparing range and text through an alert dialog is ineffective. Syntax text = range.
toString(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. Look at the output below.</p> <p id="log"></p> JavaScript const range = document.createRange(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); document.getElementById('log').textContent = range.
toString(); Result Specifications Specification Status Comment DOMThe definition of 'Range.
toString()' in that specification. Living Standard No change.
...tEndAfter(document.getElementsByTagName('b').item(1), 0); document.getElementById('log').textContent = range.
toString(); Result Specifications Specification Status Comment DOMThe definition of 'Range.
toString()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.
toString()' in that specification. Obsolete Initial specification. ...
Selection.toString() - Web APIs
The Selection.
toString() method returns a string currently being represented by the selection object, i.e. the currently selected text. Syntax sel.
toString() Return value A string representing the selection. Description This method returns the currently selected text. In JavaScript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getSelection()) // What is called alert(window.getSelection().
toString()) // What is actually being effectively called. Specifications Specification Status Comment Selection APIThe definition of 'Selection:
toString()' in that specification. Working Draft Current Browser compatibility The compatibility table on this page is generated from...
... Current Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URLSearchParams.toString() - Web APIs
The
toString() method of the URLSearchParams interface returns a query string suitable for use in a URL. Note: This method returns the query string without the question mark. This is different from window.location.search, which includes it. Note: This feature is available in Web Workers. Syntax URLSearchParams.
toString() Parameters None. Return value A DOMString, without the question mark. (Returns an empty string if no search parameters have been set.) Examples let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); //Add a second foo parameter. ...
... is available in Web Workers. Syntax URLSearchParams.
toString() Parameters None. Return value A DOMString, without the question mark. (Returns an empty string if no search parameters have been set.) Examples let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); //Add a second foo parameter. params.append('foo', 4); console.log(params.
toString()); //Prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new URL('https://example.com?foo=1&bar=2'); let params = url.searchParams; // or even simpler let params = new URLSearchParams('foo=1&bar=2'); Specifications Specification Status Comment URLThe definition of '
toString() (see "stringifier")' in that specification. Living Stan...
URLUtilsReadOnly.toString() - Web APIs
The URLUtilsReadOnly.
toString() stringifier method returns a DOMString containing the whole URL. It is a synonym for URLUtilsReadOnly.href. Syntax string = object.
toString(); Examples // In a Web worker, on the page https://developer.mozilla.org/URLUtilsReadOnly.href var result = window.self.
toString(); // Returns:'https://developer.mozilla.org/URLUtilsReadOnly.href' Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...lsReadOnly.href' Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Array.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified array and its elements. Syntax arr.
toString() Return value A string representing the elements of the array. Description The Array object overrides the
toString method of Object. For Array objects, the
toString method joins the array and returns one string containing each array element separated by commas. JavaScript calls the
toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ECMAScript 5 semantics Starting in JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th edition semantics, the
toString() method is generic and can be used with any object. ...
...rray element separated by commas. JavaScript calls the
toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ECMAScript 5 semantics Starting in JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th edition semantics, the
toString() method is generic and can be used with any object. Object.prototype.
toString() will be called, and the resulting value will be returned. Examples Using
toString const array1 = [1, 2, 'a', '1a']; console.log(array1.
toString()); // expected output: "1,2,a,1a" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.
toString' in that specification. ...
Boolean.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified Boolean object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax bool.
toString() Return value A string representing the specified Boolean object. Description The Boolean object overrides the
toString method of the Object object; it does not inherit Object.prototype.
toString(). For Boolean objects, the
toString method returns a string representation of the object. JavaScript calls the
toString() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objec...
...verrides the
toString method of the Object object; it does not inherit Object.prototype.
toString(). For Boolean objects, the
toString method returns a string representation of the object. JavaScript calls the
toString() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objects and values, the built-in
toString() method returns the string "true" or "false" depending on the value of the boolean object. Examples Using
toString() In the following code, flag.
toString() returns "true": var flag = new Boolean(true); var myVar = flag.
toString(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean.prototype.
toString' in that specification. ...
PR_NetAddrToString
string A buffer that will hold the converted string on output. size The size of the result buffer (string). Returns The function returns one of the following values: If successful, PR_SUCCESS. If unsuccessful, PR_FAILURE. You can retrieve the reason for the failure by calling PR_GetError. ...
Map.prototype[@@toStringTag] - JavaScript
The Map[@@
toStringTag] property has an initial value of "Map". The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Map.prototype[@@
toStringTag] Writable no Enumerable no Configurable yes Syntax Map[Symbol.
toStringTag] Examples Using
toStringTag Object.prototype.
toString.call(new Map()) // "[object Map]" Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype[@@
toStringTag]' in that specification. ...
String.prototype.toString() - JavaScript
The
toString() method returns a string representing the specified object. Syntax str.
toString() Return value A string representing the calling object. Description The String object overrides the
toString() method of the Object object; it does not inherit Object.prototype.
toString(). For String objects, the
toString() method returns a string representation of the object and is the same as the String.prototype.valueOf() method. Examples Using
toString() The following example displays the string value of a String object: var x = new String('Hello world'); console.log(x.
toString()); // logs 'Hello world' Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.
toString' in that specification. ...
Mozilla internal string guide
n a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. For the purpose of this document, we will refer to the 16-bit string classes in class documentation. Every 16-bit class has an equivalent 8-bit class: Naming convention for wide and narrow string classes Wide Narrow nsAString nsACString nsString nsCString nsAu
toString nsAutoCString etc... The string classes distinguish, as part of the type hierarchy, between strings that must have a null-terminator at the end of their buffer (ns[C]String) and strings that are not required to have a null-terminator (nsA[C]String). nsA[C]String is the base of the string classes (since it imposes fewer requirements) and ns[C]String is a class derived from it. F...
... There are a number of additiona...
...most common uses of the concrete classes are as local variables, and members in classes or structs. The following is a list of the most common concrete classes. Once you are familiar with them, see the appendix describing What Class to Use When. nsString / nsCString- a null-terminated string whose buffer is allocated on the heap. Destroys its buffer when the string object goes away. nsAu
toString / nsAutoCString- derived from nsString, a string which owns a 64 code unit buffer in the same storage space as the string itself. If a string less than 64 code units is assigned to an nsAu
toString, then no extra storage will be allocated. For larger strings, a new buffer is allocated on the heap. If you want a number other than 64, use the templated types nsAu
toStringN / nsAutoCStringN. (nsAutoSt...
...And 13 more matches
Index
ility of nsISupports Proxies. 934 nsISupportsArray Interfaces, Interfaces:Scriptable, NeedsHelp, XPCOM, XPCOM Interface Reference No summary! 935 nsISupportsCString Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference This methods returns a string valued representation of the object. ...
... returns a string valued representation of the object. 936 data No summary! 937
toString No summary! 938 nsISupportsChar Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference This methods returns a string valued representation of the object. 939 data No summary! 940
toString No summary! 941 nsISupportsDouble Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference This methods returns a string valued representation of the object. 942 data No summary! 943
toString No summary! 944 nsISupportsFloat Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API...
...data No summary! 943
toString No summary! ...
...And 12 more matches
Object.create() - JavaScript
differences quickly become apparent: > "oco is: " + oco // shows "oco is: [object Object]" > "ocn is: " + ocn // throws error: Cannot convert object to primitive value Testing just a few of the many most basic built-in functions shows the magnitude of the problem more clearly: > alert(oco) // shows [object Object] > alert(ocn) // throws error: Cannot convert object to primitive value > oco.
toString() // shows [object Object] > ocn.
toString() // throws error: ocn.
toString is not a function > oco.valueOf() // shows {} > ocn.valueOf() // throws error: ocn.valueOf is not a function > oco.hasOwnProperty("p") // shows "true" > ocn.hasOwnProperty("p") // throws error: ocn.hasOwnProperty is not a function > oco.constructor // shows "Object() { [native code] }" > ocn.constructor // shows "undefin...
...e() will result in an empty array being returned. var obj = Object.create({ a: 1, b: 2 }); > console.log(Object.entries(obj)); // shows "[]" Some NON-solutions A good solution for the missing object-methods is not immediately apparent. ...
... an empty array being returned. var obj = Object.create({ a: 1, b: 2 }); > console.log(Object.entries(obj)); // shows "[]" Some NON-solutions A good solution for the missing object-methods is not immediately apparent. ...
...And 10 more matches
JXON - Archive of obsolete content
utes[oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim()); } } /* * Optional properties... this.keyLength = nLength; this.attributesLength = nAttrLen; // this.DOMNode = oXMLParent; */ /* Object.freeze(this); */ } /* * Optional methods... ...
...vValue : new vValue.constructor(vValue); } var aTmpEls = []; // loaded element nodes cache function getJXONTree (oXMLParent) { var sProp, vContent, vResult, nLength = 0, nLevelStart = aTmpEls.length, nChildren = oXMLParent.hasChildNodes() ? oXMLParent.child...
...er the GNU Public License, version 3 or later. ...
...And 8 more matches
String Quick Reference - Archive of obsolete content
possible sharing or more efficient handling of string fragments. ...
...Why: Avoid copying and conversion from literal char...
...Why: Avoid copying and conversion from literal char-based strings to UTF16 strings. Old way: use n...
...And 8 more matches
Type conversion
pes.char.array(10)(); var someCFunction = library.declare("someCFunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); someCFunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type Implicit conversion can be tested in the following way: var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.bool } ])(); myStruct.v = 1; console.log(myStruct.v.
toString()); // 'true' Boolean type Target Type Source Converted value ctypes.bool JS boolean src JS number (0 or 1) if src == 0: false if src == 1: true var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.bool } ])(); myStruct.v = true; console.log(myStruct.v.
toString()); // 'true' myStruct.v = false; console.log(myStruct.v.toStr...
...rce Converted value ctypes.bool JS boolean src JS number (0 or 1) if src == 0: false if src == 1: true var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.bool } ])(); myStruct.v = true; console.log(myStruct.v.
toString()); // 'true' myStruct.v = false; console.log(myStruct.v.
toString()); // 'false' myStruct.v = 1; console.log(myStruct.v.
toString()); // 'true' myStruct.v = 0; console.log(myStruct.v.
toString()); // 'false' myStruct.v = 10; // throws Error myStruct.v = "a"; // throws Error Integer types Target Type Source Converted value ctypes.char16_t JS string (only if its length == 1) src.charCodeAt(0) any integer types JS number (only if fits to the size) src ...
... Type Source Converted value ctypes.char16_t JS string (only if its length == 1) src.charCodeAt(0) any integer types JS number (only if fits to the size) src JS boolean if src == true: 1 if src == false: 0 var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.char16_t } ])(); myStruct.v = 0x41; console.log(myStruct.v.
toString()); // "A" myStruct.v = true; console.log(myStruct.v.
toString()); // "\x01" myStruct.v = "X"; console.log(myStruct.v.
toString()); // "X" myStruct.v = "XX"; // throws Error var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.int16_t } ])(); myStruct.v = 0x41; console.log(myStruct.v.
toString()); // 65 myStruct.v = true; console.log(myStruct.v.
toString()); // 1 m...
...And 8 more matches
Working with data
se type is newType. If the size of the new type is undefined or larger than the size of the original object's data block, TypeError is thrown. This works very much like a standard C type cast or C++ reinterpret_cast. Example: Cast an array This example shows how to cast an array of a certain type to another type. ...
...is example shows how to cast an array of a certain type to another type. ...
... console: `"ctypes.long.array(4)([ctypes.Int64("1"), ctypes.Int64("2"), ctypes.Int64("3"), ctypes.Int64("4")])"` my.addressOfElement(1).contents; // this outputs `Int64 { }` my.addressOfElement(1).contents.
toString(); // outputs: `"2"` // now this is how to get the array of long's cast to array of int's var myCasted = ctypes.cast(my.address(), ctypes.int.array(my.length).ptr).contents; myCasted.
toString(); // this outputs to browser console: `"ctypes.int.array(4)([1, 2, 3, 4])"` myCasted.addressOfElement(1).contents; // this outputs `2` myCasted.addressOfElement(1).contents.
toString(); // outputs: `"2"` Source of this, and to see wrong ways of casting, and explanation on why this is the right way to cast an array (explained by matching constructor's) see here: GitHubGIST :: _ff-addon-tutorial...
...And 8 more matches
sample2
NATURE-----" #define NS_CERT_HEADER "-----BEGIN CERTIFICATE-----" #define NS_CERT_TRAILER "-----END CERTIFICATE-----" /* Missing publically from nss versions earlier than 3.13 */ #ifndef SEC_ERROR_BASE #define SEC_ERROR_BASE (-0x2000) typedef enum { SEC_ERROR_IO = SEC_ERROR_BASE + 0, SEC_ERROR_TOKEN_NOT_LOGGED_IN = (SEC_ERROR_BASE + 155), SEC_ERROR_END_OF_LIST } SECErrorCodes; #endif /* PORT_Error
ToString introduced in nss 3.13. On earlier versions of nss that * don't support error tables, PR_Error
ToString will return "Unknown code". */ #ifndef PORT_Error
ToString #define PORT_Error
ToString(err) PR_Error
ToString((err), PR_LANGUAGE_I_DEFAULT) #endif /* sample 6 commands */ typedef enum { GENERATE_CSR, ADD_CERT_TO_DB, SAVE_CERT_TO_HEADER, ENCRYPT, DECRYPT, SIGN, VERIFY, UNKNOWN } CommandType; typedef...
...This may take a few moments...\n\n"); privKey...
...NickName); goto cleanup; } } arena = cert->arena; algID = SEC_GetSignatureAlgorithmOidTag(privKey->keyType, hashAlgTag); if (algID == SEC_OID_UNKNOWN) { PR_fprintf(PR_STDERR, "Unknown key or hash type for issuer.\n"); goto cleanup; } rv = SECOID_SetAlgorithmID(arena, &cert->signature, algID, 0); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not set signature algorithm id.\n%s\n", PORT_Error
ToString(rv)); goto cleanup; } /* we only deal with cert v3 here */ *(cert->version.data) = 2; cert->version.len = 1; der.len = 0; der.data = NULL; dummy = SEC_ASN1EncodeItem (arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate)); if (!dummy) { PR_fprintf(PR_STDERR, "Could not encode certificate.\n"); goto cleanup; } result = (SECItem *) PORT_ArenaZAlloc (arena, sizeof (SECItem)); if (result == NULL)...
...And 7 more matches
Bytecode Descriptions
a global scope: typeof x compiles to GetGName "x"; Typeof. typeof (0, x) compiles to GetGName "x"; TypeofExpr. Emitting the same bytecode for these two expressions would be a bug. Per spec, the latter throws a ReferenceError if x doesn't exist. Format: JOF_IC Pos Stack: val => (+val) The unary + operator. +val doesn't do any actual math. It just calls ToNumber(val). The conversion can call .
toString()/.valueOf() methods and can throw. The result on success is always a Number. (Per spec, unary - supports BigInts, but unary + does not.) Format: JOF_IC Neg Stack: val => (-val) The unary - operator. Convert val to a numeric value, then push -val. The conversion can call .
toString()/.valueOf() methods and can throw. The result on success is always numeric. Format: JOF_IC BitNot Stack: val =...
...The result on success is always an Int32 or BigInt value. Format: JOF_IC Not Stack: val => (!val) The logical NOT operator (!). val is first converted with ToBoolean, then logically negated. ...
... (!val) The logical NOT operator (!). val is first converted with ToBoolean, then logically negated. The result is always a boolean value. This does not call user-defined methods and can't throw. Format: JOF_IC Binary operators BitOr, BitXor, BitAnd Stack: lval, rval => (lval OP rval) Binary bitwise operations (|, ^, &). The arguments are converted to integers first. The conversion can call .
toString()/.valueOf() methods and can throw. The result on success is always an Int32 or BigInt Value. Format: JOF_IC Eq, Ne Stack: lval, rval => (lval OP rval) Loose equality operators (== and !=). Pop two values, compare them, and push the boolean result. The comparison may perform conversions that call .
toString()/.valueOf() methods and can throw. Implements: Abstract Equality Comparison. Format: JO...
...And 7 more matches
RangeError: radix must be an integer - JavaScript
The JavaScript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the Number.prototype.
toString() or the BigInt.prototype.
toString() method was specified and is not between 2 and 36. Message RangeError: invalid argument (Edge) RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox) RangeError:
toString() radix argument must be between 2 and 36 (Chrome) Error type RangeError What went wrong? The optional radix parameter of the Number.prototype.
toString() or the BigInt.prototype.
toString() method was specified. Its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. For example, the decimal (base 10) number 169 is repr...
...arameter's value limited to 36? A radix that is larger than 10 uses alphabetical characters as digits; therefore, the radix can't be larger than 36, since the Latin alphabet (used by English and many other languages) only has 26 characters. ...
...imited to 36? A radix that is larger than 10 uses alphabetical characters as digits; therefore, the radix can't be larger than 36, since the Latin alphabet (used by English and many other languages) only has 26 characters. The most common radixes: 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers. ...
...And 7 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
m; SECOidTag algtag; PK11RSAGenParams rsaparams; void *params; SECKEYPrivateKey *privKey = NULL; SECStatus rv; unsigned char randbuf[BLOCKSIZE + 1]; rv = GenerateRandom(randbuf, BLOCKSIZE); if (rv != SECSuccess) { fprintf(stderr, "Error while generating the random numbers : %s\n", PORT_Error
ToString(rv)); goto cleanup; } PK11_RandomUpdate(randbuf, BLOCKSIZE); switch (keytype) { case rsaKey: rsaparams.keySizeInBits = size; rsaparams.pe = publicExponent; mechanism = CKM_RSA_PKCS_KEY_PAIR_GEN; algtag = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION; params ...
...gnatureAlgorithmOidTag(privKey->keyType, hashAlgTag); if (algID == SEC_OID_UNKNOWN) { PR_fprintf(PR_STDERR, "Unknown key or hash type for issuer.\n"); goto cleanup; } rv = SECOID_SetAlgorithmID(arena, &cert->signature, algID, 0); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not set signature algorithm id.\n%s\n", PORT_Error
ToString(rv)); goto cleanup; } /* we only deal with cert v3 here */ *(cert->version.data) = 2; cert->version.len = 1; der.len = 0; der.data = NULL; dummy = SEC_ASN1EncodeItem (arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate)); if (!dummy) { PR_fprintf(PR_STDERR, "Could not encode certificate.\n"); ...
...ORT_ArenaZAlloc (arena, sizeof (SECItem)); if (result == NULL) { PR_fprintf(PR_STDERR, "Could not allocate item for certificate data.\n"); goto cleanup; } rv = SEC_DerSignData(arena, result, der.data, der.len, privKey, algID); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not sign encoded certificate data : %s\n", PORT_Error
ToString(rv)); /* result allocated out of the arena, it will be freed * when the arena is freed */ result = NULL; goto cleanup; } cert->derCert = *result; cleanup: if (caPrivateKey) { SECKEY_DestroyPrivateKey(caPrivateKey); } return result; } /* * MakeV1Cert */ static CERTCertificate * MakeV1Cert(CERTCertDBHandle *handle...
...And 6 more matches
XPCOM primitive
such as nsITransferable.setTransferData(), require primitives. ...
...sID @mozilla.org/supports-id;1 [scriptable, uuid(d18290a0-4a1c-11d3-9890-006008962422)] interface nsISupportsID : nsISupportsPrimitive { attribute nsIDPtr data; string
toString(); }; AString nsISupportsString @mozilla.org/supports-string;1 [scriptable, uuid(d79dc970-4a1c-11d3-9890-006008962422)] interface nsISupportsString : nsISupportsPrimitive { attribute AString data; wstring
toString(); }; PRBool nsISupportsPRBool @mozilla.org/supports-PRBool;1 [scriptable, uuid(ddc3b490-4a1c-11d3-9890-006008962422)] interface nsISupportsPRBool : nsISupportsPrimitive { attribute PRBool data; string
toString(); }; PRUint8 nsISupportsPRUint8 @mozilla.org/supports-PRUint8;1 [scriptable, uuid(dec2e4e0-4a1c-11d3-9890-006008962422)] interface nsISupportsPRUint8 : nsISupportsPrimitive { ...
...lla.org/supports-PRBool;1 [scriptable, uuid(ddc3b490-4a1c-11d3-9890-006008962422)] interface nsISupportsPRBool : nsISupportsPrimitive { attribute PRBool data; string
toString(); }; PRUint8 nsISupportsPRUint8 @mozilla.org/supports-PRUint8;1 [scriptable, uuid(dec2e4e0-4a1c-11d3-9890-006008962422)] interface nsISupportsPRUint8 : nsISupportsPrimitive { attribute PRUint8 data; string
toString(); }; PRUint16 nsISupportsPRUint16 @mozilla.org/supports-PRUint16;1 [scriptable, uuid(dfacb090-4a1c-11d3-9890-006008962422)] interface nsISupportsPRUint16 : nsISupportsPrimitive { attribute PRUint16 data; string
toString(); }; PRUint32 nsISupportsPRUint32 @mozilla.org/supports-PRUint32;1 [scriptable, uuid(e01dc470-4a1c-11d3-9890-006008962422)] interface nsISupportsPRUint32 : nsISuppor...
...And 6 more matches
Index
igned 64bit integer. 75 JS::ToNumber JSAPI Reference, SpiderMonkey JS::ToNumber converts a JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. 76 JS::ToPrimitive JSAPI Reference, SpiderMonkey JS::ToPrimitive converts a JavaScript object, obj, to a primitive value using ECMAScript 6 ToPrimitive. 77 JS::
ToString JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::
ToString returns a string representation of a JavaScript value. 78 JS::ToUint16 JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::ToInt16 converts a JavaScript value to an unsigned 16bit integer. It implements the ToInt16 operator described in ECMA 262-3 ?9.7. 79 JS::ToUint32 JSAPI Re...
... is a jsval constant that represents the JavaScript value undefined. 180 JSVAL_ZERO JSAPI Reference, Obsolete, SpiderMonkey JSVAL_ZERO is equivalent to INT_TO_JSVAL(0). 181 JSVersion JSAPI Reference, SpiderMonkey The JSVersion enumerated type includes the following values. Each version has a name, which is a string used by JS_StringToVersion and JS_Version
ToString. 182 JSXDRObjectOp JSAPI Reference, Obsolete, Reference, Reference(2), SpiderMonkey Serialize or deserialize an object, given an XDR state record representing external data. See jsxdrapi.h. 183 JS_ASSERT_STRING_IS_FLAT JSAPI Reference, Reference, Reference(2), SpiderMonkey JS_ASSERT_STRING_IS_FLAT asserts the string is flattened, and returns a pointer to ...
...eference, Reference, Reference(2), SpiderMonkey JS_ValueToId converts a specified JS::Value, v, to a jsid. If v is an integer, *idp receives an integer jsid. Otherwise, if E4X support is enabled and v is an object, *idp receives an object jsid. Otherwise, *idp receives an interned string jsid based on the value of v. If v is not a string, it is converted to a string as if by calling JS_Value
ToString. 498 JS_ValueToInt32 JSAPI Reference, Obsolete, SpiderMonkey JS_ValueToInt32 converts a specified JS value, v, to a 32-bit signed integer (-2147483648 to 2147483647). First it converts v to a floating-point number as if by calling JS::ToNumber. If the result is NaN, an infinity, or a number outside the 32-bit range, JS_ValueToInt32 reports an error and conversion fails. Other...
...And 4 more matches
Index - Web APIs
he protocol scheme of the URL, including the final ':'. 1699 HTMLHyperlinkElementUtils.search API, Experimental, HTMLHyperlinkElementUtils, Property, Reference, URL API The HTMLHyperlinkElementUtils.search property is a search string, also called a query string, that is USVString containing a '?' followed by the parameters of the URL. 1700 HTMLHyperlinkElementUtils.
toString() API, Experimental, HTMLHyperlinkElementUtils, Location, Method, Stringifier, URL API The HTMLHyperlinkElementUtils.
toString() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. 1701 HTMLHyperlinkElementUtils.username API, Experimental, HTMLHyperlinkElementUtils, Property, Reference, URL API ...
...startOffset API, DOM, Property, Range The Range.startOffset read-only property returns a number representing where in the startContainer the Range starts. 3584 Range.surroundContents() API, DOM, Method, Range The Range.surroundContents() method moves content of the Range into a new node, placing the new node at the start of the specified range. 3585 Range.
toString() API, DOM, Method, Range, Stringifier The Range.
toString() method is a stringifier returning the text of the Range. 3586 ReadableByteStreamController API, Experimental, Fetch, Interface, ReadableByteStreamController, Reference, Streams The ReadableByteStreamController interface of the Streams API represents a controller allowing control of a ReadableStream's state ...
...es until Firefox 29. It was removed in bug 949445 and should not be used. 3916 Selection.setBaseAndExtent() API, Experimental, Method, Reference, Selection, setBaseAndExtent The setBaseAndExtent() method of the Selection interface sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them. 3917 Selection.
toString() API, Experimental, HTML Editing, Method, Reference, Selection The Selection.
toString() method returns a string currently being represented by the selection object, i.e. the currently selected text. 3918 Selection.type API, Experimental, Property, Reference, Selection, Type The type read-only property of the Selection interface returns a DOMString describing the ty...
...And 4 more matches
StringView - Archive of obsolete content
al Public License, version 3 or later. ...
...hrOffset) ? nChrOffset : 0; nRawEnd = isFinite(nChrLen) ? ...
...For actually supported values see here. buffer Read only arrayBuffer The buffer to be shared between stringView.rawData and stringView.bufferView view references. rawData Read only arrayBufferView A...
...And 3 more matches
Standard OS Libraries
ow containing the pointer (as with gdk_window_at_pointer()), or NULL if the window containing the pointer isn't known to GDK. ...
...dkWindowPtr = gdk_get_default_root_window(); console.info('winRoot_GdkWindowPtr:', winRoot_GdkWindowPtr, winRoot_GdkWindowPtr.
toString()); // gdk2 var x = gint(); var y = gint(); var mask = GdkModifierType(); var win_underMouse = gdk_window_get_pointer( winRoot_GdkWindowPtr, x.address(), y.address(), mask.address() ); console.info('win_underMouse:', win_underMouse, win_underMouse.
toString()); console.info('x:', x, x.
toString()); console.info('y:', y, y.
toString()); console.info('mask:', mask, mask.
toString()); gdk.close(); Example: gdk_window_get_device_position This example works only for GDK3, as the function gdk_window_get_device_position was not available in GDK2, for GDK2 equivalent see above WARNING THIS EXAMPLE DOES NOT WORK YET IT NEEDS SOME BUG FIXING Components.u...
...The list of the exposed symbols/functions can be found here: GNOME Developer :: GTK+ Reference Manual. Example: ... // placeholder - example soon to come X11 X11 runs primarily on UNIX(R) and UNIX-like...
...And 3 more matches
How to embed the JavaScript engine
*/ static JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, ...
...*/ static JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, ...
...*/ static JSClass global_class = { "global...
...And 2 more matches
CData
Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. ...
...ters None. Return value A string that, ideally, should be able to be evaluated to produce a new CData object containing a copy of the original object. However, this only works if the object's type happens to be bound to an appropriate name in scope. In theory, in other words, the following JavaScript expression should return a copy of the original CData object: eval(dataObject.toSource());
toString() Returns a string identifying the data. String
toString(); Parameters None. Return value A string identifying the data. Methods available on string objects These methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readString() Converts a character array to a JavaScript string. 8-bit strings are...
...Noitidart/_scratchpad MDNFirefox" // tries to do read string on stringPtr, if it fails then it falls to read as jschar var readJSCharString = function() { var assumpt...
...And 2 more matches
Inheritance and the prototype chain - JavaScript
rated by the console. After running this code, the console should have displayed an object that looks similar to this. { constructor: f doSomething(), __proto__: { constructor: f Object(), hasOwnProperty: f hasOwnProperty(), isPrototypeOf: f isPrototypeOf(), propertyIsEnumerable: f propertyIsEnumerable(), toLocaleString: f toLocaleString(),
toString: f
toString(), valueOf: f valueOf() } } We can add properties to the prototype of doSomething(), as shown below. function doSomething(){} doSomething.prototype.foo = "bar"; console.log( doSomething.prototype ); This results in: { foo: "bar", constructor: f doSomething(), __proto__: { constructor: f Object(), hasOwnProperty: f hasOwnProperty(), i...
...To use the new operator, simply call the function normally except prefix it with new. Calling a function with the new operator returns an object that is an instance of the function. Properties can then be added onto this object. Try the following c...
...To use the new operator, simply call the function normally except prefix it with new. Calling a function with the new operator returns an object that is an instance of the function. Properties can then be added onto this object. Try the following code: functi...
...And 2 more matches
Communicating using "postMessage" - Archive of obsolete content
e constructor: panel = require("sdk/panel").Panel({ onMessage: function(contentScriptMessage) { // Handle message from the content script } }); Message Events Versus User-Defined Events You can use message events as an alternative to user-defined events: var pageModScript = "window.addEventListener('mouseover', function(event) {" + " self.postMessage(event.target.
toString());" + "}, false);"; var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.on('message', function(message) { console.log('mouseover: ' + message); }); } }); The reason to prefer user-defined events is that as soon as you need to send more than one type of message, then both sen...
...s to send mouseout events as well as mouseover. ...
...ssage({" + " kind: 'mouseover'," + " element: event.target.
toString()" + " });" + "}, false);" + "window.addEventListener('mouseout', function(event) {" + " self.postMessage({" + " kind: 'mouseout'," + " element: event.target.
toString()" + " });" + " }, false);" var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.on('message', function(message) { switch(message.kind) { case 'mouseover': console.log('mouseover: ' + message.element); break; case 'mouseout': cons...
...e.log('mouseover: ' + message.element); break; case 'mouseout': console.log('mouseout: ' + message.element); break; } }); } }); Implementing the same add-on with user-defined events is shorter and more readable: var pageModScript = "window.addEventListener('mouseover', function(event) {" + " self.port.emit('mouseover', event.target.
toString());" + "}, false);" + "window.addEventListener('mouseout', function(event) {" + " self.port.emit('mouseout', event.target.
toString());" + "}, false);"; var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.port.on('mouseover', func...
context-menu - Archive of obsolete content
your "context" listeners can also return strings. When a "context" listener returns a string, it becomes the item's new label. This item implements the aforementioned search example: var cm = require("sdk/context-menu"); cm.Item({ label: "Search Google", context: cm.SelectionContext(), contentScript: 'self.on("context", function () {' + ' var text = window.getSelection().
toString();' + ' if (text.length > 20)' + ' text = text.substr(0, 20) + "...";' + ' return "Search Google for " + text;' + '});' }); The "context" listener gets the window's current selection, truncating it if it's too long, and includes it in the returned string. When the item is shown, its label will be "Search Google for text", w...
... i=0; i < cmitems.length; i++) cmitems[i].tooltipText = cmitems[i].value.substring(36); } }); Globals Constructors Item(options) Creates a labeled menu item that can perform an action when clicked. Parameters options : object Required options: Name Type label string The item's label. It must either be a string or an object that implements
toString(). Optional options: Name Type image string The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. data string An optional arbitrary value to associate with the item. It must be either a string or an object that implements
toString(). It will be passed...
...nction will be called when the content script calls self.postMessage. It will be passed the data that was passed to postMessage. Menu(options) Creates a labeled menu item that expands into a submenu. Parameters options : object Required options: Name Type label string The item's label. It must either be a string or an object that implements
toString(). items array An array of menu items that the menu will contain. Each must be an Item, Menu, or Separator. Optional options: Name Type image string The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. context value If the men...
...the item to update its label later. image The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. You can set this after creating the item to update its image later. To remove the item's image, set it to null. data An optional arbitrary value to associate with the item. It must be either a string or an object that implements
toString(). It will be passed to click listeners. You can set this after creating the item to update its data later. context A list of declarative contexts for which the menu item will appear in the context menu. Contexts can be added by calling context.add() and removed by called context.remove(). parentMenu The item's parent Menu, or null if the item is contained in the top-level context menu. This ...
Finding window handles - Archive of obsolete content
ForegroundWindow( * __in_ HWND hWnd * ); */ var SetForegroundWindow = user32.declare('SetForegroundWindow', ctypes.winapi_abi, ctypes.bool, // return BOOL ctypes.voidptr_t // HWND ); var hwnd = ctypes.voidptr_t(ctypes.UInt64(hwndString)); var rez_SetForegroundWindow = SetForegroundWindow(hwnd); console.log('rez_SetForegroundWindow:', rez_SetForegroundWindow, rez_SetForegroundWindow.
toString()); user32.close(); Mac OS X Objective-C Components.utils.import('resource://gre/modules/Services.jsm'); var browserWindow = Services.wm.getMostRecentWindow('navigator:browser'); if (!browserWindow) { throw new Error('No browser window found'); } var baseWindow = browserWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) ...
...The string is made into an actual GdkWindow* like this: var GdkWindow = ctypes.StructType('GdkWindow'); var GDKWindowPtrString = baseWindow.nativeHandle; var GdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); Working with GdkWindow* GdkWindow* to XI...
...on.html#gdk-x11-get-server-time var gdk_x11_get_server_time = gdk.declare('gdk_x11_get_server_time', ctypes.default_abi, guint32, GdkWindow.ptr); var browserWindow_madeIntoGdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); var gptr = gpointer(); var rez_gwgud = gdk_window_get_user_data(browserWindow_madeIntoGdkWinPtr, gptr.address()); console.info('rez_gwgud:', rez_gwgud, /*rez_gwgud.
toString(),*/ uneval(rez_gwgud)); // return is void so cant do .
toString on it var browserWindow_madeIntoGtkWindowPtr = ctypes.cast(gptr, GtkWindow.ptr); // focusing window this way is better, so it maintains proper history in case you or some other app want to focus "most recent window" by timestamp // var rez_gst = gdk_x11_get_server_time(browserWindow_madeIntoGdkWinPtr); // console.info('rez_gst:', r...
...to see the messy code see here: https://gist.github.com/Noitidart/60aab0a96f060240614f#file-_ff-addon-snippet-x11_focusmostrecentwindowofpid-js-L354 gdk.close(); x11.close(); See Also js-ctypes - How to use C from Javascript...
The new nsString class implementation (1999) - Archive of obsolete content
nsStrImpl& aSource, PRInt32 aCount,PRBool aIgnoreCase); }; nsString The nsString class is still with us as a subclass (wrapper) of nsStrImpl. By default, nsStrings use a 2-byte UCS2 character storage model. The nsString class is very lightweight since it gets its functionality from the nsStrImpl static library. In addition to the nsStrImpl API shown above, nsString, nsAu
toString and nsCString all offer additional API's (that all degrade to those found in nsStrImpl) for construction, searching and comparison. Also note that the new nsString interface mimics fully the interface in the existing nsString class found in mozilla/base/src/nsString.h. nsAu
toString We still offer an nsAu
toString that provides its own stack based buffer. This very useful class allows programmers t...
...This means that you can continue to use efficient (temporary) stack buffers for string storage with the bonus of storage pools that serve your specific need. ...
...Sounds complicated, but it's really easy). This class fully interoperates with nsString and nsStrImpl. nsCString The new nsCString class shares the same API with nsString, but uses a 1-byte ASCII character storage model. This will allow programmers to use the nsString API's like a standard char* without incurring the 2-byte per character overhead. This class fully interoperates with nsString, nsAu
toString and nsStrImpl. nsIString Naturally we will need include an nsIString interface onto the nsStrImpl/nsString classes. I won't repeat it's interface here since it is basically a restatement (in XPCOM terms) of the nsString interface. Usage Patterns How To Use These Classes To increase the portability, thread and process safety of Gecko, I suggest the following rules regarding the use of each of our ...
... <center> String Class</center> <center> Where To Use</center> nsStrImpl Use to pass strings between modules who have linked the nsStrImpl function library. nsString Use these locally in objects who span of control is known to live within your own process. These should typically not be exposed to objects in other modules. nsAu
toString Use these locally in cases where you don't want to incur heap allocation unless absolutely necessary. nsCString Same as nsString, but should be used with caution because of localization concerns. nsIString Use to pass strings between modules that may not use nsStrImpl implementation. This is the most generic approach, but offers reference counted strings. There ar...
LiveConnect Overview - Archive of obsolete content
o a Java method, Java simply unwraps the object; in a few situations, the object is coerced into another data type according to the rules described in the following table: Java parameter type Conversion rules Any interface or class that is assignment-compatible with the unwrapped object. The object is unwrapped. java.lang.String The object is unwrapped, the
toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String. byte char double float int long short The object is unwrapped, and either of the following situations occur: If the unwrapped Java object has a doubleValue method, the JavaArray or JavaObject is converted to the value returned by this m...
... method, Java converts the object according to the rules described in the following table: Java parameter type Conversion rules java.lang.Class The object is unwrapped. netscape.javascript.JSObject java.lang.Object The JavaClass object is wrapped in a new instance of netscape.javascript.JSObject. java.lang.String The object is unwrapped, the
toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String. boolean In JavaScript 1.3 and later versions, the object is unwrapped and either of the following situations occur: If the object is null, it is converted to false. If the object has any other value, it is converted to true. In JavaScript 1.2 and ear...
...n you pass any other JavaScript object as a parameter to a Java method, Java converts the object according to the rules described in the following table: Java parameter type Conversion rules netscape.javascript.JSObject java.lang.Object The object is wrapped in a new instance of netscape.javascript.JSObject. java.lang.String The object is unwrapped, the
toString method of the unwrapped object is called, and the result is returned as a new instance of java.lang.String. byte char double float int long short The object is converted to a value using the logic of the ToPrimitive operator described in ECMA-262. The PreferredType hint used with this operator is Number. boolean In JavaScript 1.3 and later versi...
...pt pseudo-Array object; this object behaves just like a JavaScript Array object: you can access it with the syntax arrayName[index] (where index is an integer), and determine its length with arrayName.length. A Java object of any other class is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object: Converting this wrapper to a string calls the
toString method on the original object. Converting to a number calls the doubleValue method, if possible, and fails otherwise. Converting to a boolean in JavaScript 1.3 and later versions returns false if the object is null, and true otherwise. Converting to a boolean in JavaScript 1.2 and earlier versions calls the booleanValue method, if possible, and fails otherwise. Note that instances ...
JSObject - Archive of obsolete content
al Evaluates a JavaScript expression. getMember Retrieves the value of a property of a JavaScript object. getSlot Retrieves the value of an array element of a JavaScript object. removeMember Removes a property of a JavaScript object. setMember Sets the value of a property of a JavaScript object. setSlot Sets the value of an array element of a JavaScript object.
toString Converts a JSObject to a string. The netscape.javascript.JSObject class has the following static method: getWindow Gets a JSObject for the window containing the given applet. call Method. Calls a JavaScript method. Equivalent to "this.methodName(args[0], args[1], ...)" in JavaScript. Declaration public Object call(String methodName, Object args[]) equals Method. Determines if ...
...mber(String name) setMember Method. Sets the value of a property of a JavaScript object. Equivalent to "this.name = value" in JavaScript. ...
...erty of a JavaScript object. Equivalent to "this.name = value" in JavaScript. Declaration public void setMember(String name, Object value) setSlot Method. ...
...in JavaScript. Declaration public void setMember(String name, Object value) setSlot Method. Sets the value of an array element of a JavaScript object. ...
TypeScript support in Svelte - Learn web development
with properties of type JsonValue. We will import our JsonValue type and use it accordingly. ...
... // receives the key of the local storage and an initial value const
toString = (value: JsonValue) => JSON.stringify(value, null, 2) // helper function const toObj = JSON.parse // helper function if (localStorage.getItem(key) === null) { // item not present in local storage localStorage.setItem(key,
toString(initial)) // initialize local storage with initial value } const saved = toObj(localStorage.getItem(key)) // convert to object const { subscribe, set, update } = writable(saved) // create the underlying writable store return { subscribe, set: (value: JsonValue) => { localStorage.setItem(key,
toString(v...
...hen we'll use the the T type appropriately. ...
... // receives the key of the local storage and an initial value const
toString = (value: T) => JSON.stringify(value, null, 2) // helper function const toObj = JSON.parse // helper function if (localStorage.getItem(key) === null) { // item not present in local storage localStorage.setItem(key,
toString(initial)) // initialize local storage with initial value } const saved = toObj(localStorage.getItem(key)) // convert to object const { subscribe, set, update } = writable<T>(saved) // create the underlying writable store return { subscribe, set: (value: T) => { localStorage.setItem(key,
toString(value)) ...
JSAPI reference
JSAPI 27 JS_GetOptions Obsolete since JSAPI 27 JS_ToggleOptions Obsolete since JSAPI 27 enum JSVersion JSVERSION_ECMA_3 JSVERSION_1_6 JSVERSION_1_7 JSVERSION_1_8 JSVERSION_ECMA_5 JSVERSION_DEFAULT JSVERSION_UNKNOWN JSVERSION_LATEST JS_GetImplementationVersion JS_GetVersion JS_SetVersionForCompartment Added in SpiderMonkey 31 JS_StringToVersion JS_Version
ToString JS_SetVersion Obsolete since JSAPI 25 JS::CurrentGlobalOrNull Added in SpiderMonkey 31 JS_GetGlobalForScopeChain Obsolete since JSAPI 25 JS_GetGlobalObject Obsolete since JSAPI 24 JS_SetGlobalObject Obsolete since JSAPI 25 JS_InitClass JS_InitStandardClasses JS_ResolveStandardClass JS_EnumerateStandardClasses JS_EnumerateResolvedStandardClasses Obsolete since JSAPI 24 ...
...S_AddArgumentFormatter Obsolete since JSAPI 18 JS_RemoveArgumentFormatter Obsolete since JSAPI 18 The following functions convert JS values to various types. They can be safely applied to jsvals of any type. They may return new objects. For example, JS_ValueToObject(cx, s) where s is a string creates a new String wrapper object. These functions may call JavaScript methods. ...
... since JSAPI 18 JS_RemoveArgumentFormatter Obsolete since JSAPI 18 The following functions convert JS values to various types. They can be safely applied to jsvals of any type. They may return new objects. For example, JS_ValueToObject(cx, s) where s is a string creates a new String wrapper object. These functions may call JavaScript methods. For example, JS_Value
ToString(cx, obj) may call obj.
toString(). JS::ToBoolean Added in SpiderMonkey 17 JS::ToUint16 Added in SpiderMonkey 17 JS::ToInt32 Added in SpiderMonkey 17 JS::ToUint32 Added in SpiderMonkey 17 JS::ToInt64 Added in SpiderMonkey 17 JS::ToUint64 Added in SpiderMonkey 17 JS::ToNumber Added in SpiderMonkey 17 JS::
ToString Added in SpiderMonkey 31 JS::OrdinaryToPrimitive Added in SpiderMonkey 38 JS_ValueToConstructor JS_ValueT...
...These macros must not be applied to values that are not known to be the right type. Like C casts, they may cause crashes if applied to incorrect values. They never create new objects or call into JavaScript code. BOOLEAN_TO_JSVALObsolete since JSAPI 42 INT_TO_JSVAL Obsolete since JSAPI 42 ...
Window.getSelection() - Web APIs
When called on an <iframe> that is not displayed (eg. ...
...rn a Selection object with Selection.type set to None. Examples function foo() { var selObj = window.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's
toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.
toString() is automatically called when it is passed to window.alert(). However, attempting to use a JavaScript String property or method such as length or substr di...
... selectedText is a string (Selected text). Related objects You can call Document.getSelection(), which works identically to Window.getSelection(). ...
...is automatically called when it is passed to window.alert(). However, attempting to use a JavaScript String property or method such as length or substr directly on a Selection object will result in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its
toString() method directly: var selectedText = selObj.
toString(); selObj is a Selection object. selectedText is a string (Selected text). Related objects You can call Document.getSelection(), which works identically to Window.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <textarea> and <input> elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange() or the selecti...
Closures - JavaScript
ed and memory consumption. For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). ...
...nce, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). ...
...ing(); this.message = message.
toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; } Because the previous code does not take advantage of the benefits of using closures in this particular instance, we could instead rewrite it to avoid using closure as follows: function MyObject(name, message) { this.name = name.
toString(); this.message = message.
toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } }; However, redefining the prototype is not recommended. ...
...ect(name, message) { this.name = name.
toString(); this.message = message.
toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } }; However, redefining the prototype is not recommended. The following example instead appends to the existing prototype: function MyObject(name, message) { this.name = name.
toString(); this.message = message.
toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; }; In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See Details of the Object Model for more. ...
core/heritage - Archive of obsolete content
eritance and ancestors prototypes of the classes passed under implements option are ignored. As mentioned before you could pass constructors that were not created using Class function as long as they have proper prototype setup. ...
...ors prototypes of the classes passed under implements option are ignored. As mentioned before you could pass constructors that were not created using Class function as long as they have proper prototype setup. ...
...sary: var Point = Class({ initialize: function initialize(x, y) { this.x = x; this.y = y; },
toString: function
toString() { return this.x + ':' + this.y; } }) var Pixel = Class({ extends: Point, implements: [ Color ], initialize: function initialize(x, y, color) { Color.prototype.initialize.call(this, color); Point.prototype.initialize.call(this, x, y); },
toString: function
toString() { return this.hex() + '@' + Point.prototype.
toString.call(this) } }); var pixel = Pixel(11, 23, 'CC3399'); pixel.
toString(); // => #CC3399@11:23 pixel instanceof Pixel // => true pixel instanceof Point // => true extend Module exports extend utility function, that is useful for creating objects that inherit from other...
Add a Context Menu Item - Archive of obsolete content
is displayed whenever something in the page is selected. When it's clicked, the selection is sent to the main add-on code, which just logs it: var contextMenu = require("sdk/context-menu"); var menuItem = contextMenu.Item({ label: "Log Selection", context: contextMenu.SelectionContext(), contentScript: 'self.on("click", function () {' + ' var text = window.getSelection().
toString();' + ' self.postMessage(text);' + '});', onMessage: function (selectionText) { console.log(selectionText); } }); Try it: run the add-on, load a web page, select some text and right-click. You should see the new item appear: Click it, and the selection is logged to the console (or the shell, if you're running an instance of Firefox from the command l...
... From Firefox 35 you can specify an access key using the accesskey option. This must be a single-character string. Pressing the key selects the option when the...
...cess key using the accesskey option. This must be a single-character string. Pressing the key selects the option when the context menu is open: var contextMenu = require("sdk/context-menu"); var menuItem = contextMenu.Item({ label: "Log Selection", context: contextMenu.SelectionContext(), contentScript: 'self.on("click", function () {' + ' var text = window.getSelection().
toString();' + ' self.postMessage(text);' + '});', accesskey: "l", onMessage: function (selectionText) { console.log(selectionText); } }); Learning More To learn more about the context-menu module, see the context-menu API reference. ...
Creating Reusable Modules - Archive of obsolete content
ion Firefox has built-in support for hash functions, exposed via the nsICryptoHash XPCOM interface The documentation page for that interface includes an example of calculating an MD5 hash of a file's contents, given its path. ...
...c, i) => toHexString(hash.charCodeAt(i))).join(""); return s; } Putting it together The complete add-on adds a button to Firefox: when the user clicks the button, we ask them to select a file, compute the hash, and log the hash to the console: var {Cc, Ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function toHexString(charCode) { return ("0" + charCode.
toString(16)).slice(-2); } function md5File(path) { var f = Cc["@mozilla.org/file/local;1"] .createInstance(Ci.nsILocalFile); f.initWithPath(path); var istream = Cc["@mozilla.org/network/file-input-stream;1"] .createInstance(Ci.nsIFileInputStream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = Cc["@mozilla.org/security/hash;1"] .createInstan...
...le... } return path; } exports.promptForFile = promptForFile; md5.js Next, create another file in "lib", called "md5.js". ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
XPIs, as it provides the best experience to users. Web Script Example <script type="application/javascript"> <!-- function install (aEvent) { for (var a = aEvent.target; a.href === undefined;) a = a.parentNode; var params = { "Foo": { URL: aEvent.target.href, IconURL: aEvent.target.getAttribute("iconURL"), Hash: aEvent.target.getAttribute("hash"),
toString: function () { return this.URL; } } }; InstallTrigger.install(params); return false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconURL="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return install(event);">Install Extension!</a> Let's go through this piece by piece. The HTML <a> is the install link. The href attr...
...ile to disk easily by right clicking on the link and choosing "Save Link As..." When the link is clicked it calls the function install passing the event object as the parameter. The install first creates a parameter block: var params = { "Foo": { URL: aEvent.target.href, IconURL: aEvent.target.getAttribute("iconURL"), Hash: aEvent.target.getAttribute("hash"),
toString: function () { return this.URL; } }; This specifies the display name (Foo) for use in the confirmation dialog, the URL to the extension (which is the link href, recall), the Icon URL to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a
toString function which will allow this code to work with versions of Firefox 0.8 and earlier. ...
...els in size. Hash The Hash property specifies a cryptographic hash of the XPI file contents. This is used to verify the downloaded file, to protect against a corrupted file being served by a mirror download server, for example. You can use any hash function supported by nsICryptoHash. The hash is specified as hash function:hash value, for example, sha1:28857e60d043447c5f4550853f2d40770b326a13.
toString() The
toString() property should return the XPI URL, for compatibility with Firefox browsers older than version 1.0, and other applications such as Seamonkey. Themes Pretty much everything I've described applies to themes too, except you'll use the installChrome function. Because so many sites installed extensions by direct-linking the XPI file and relying on content handling to invoke the con...
jspage - Archive of obsolete content
turn($type(c)===b); };}};(function(){var a={Array:Array,Date:Date,Function:Function,Number:Number,RegExp:RegExp,String:String};for(var h in a){new Native({name:h,initialize:a[h],protect:true}); }var d={"boolean":Boolean,"native":Native,object:Object};for(var c in d){Native.typize(d[c],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","
toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]}; for(var e in f){for(var b=f[e].length;b--;){Native.genericize(a[e],f[e][b],true);}}})();var Hash=new Native({name:"Hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getClean()); }for(var b in a){th...
...((c=="array"||c=="collection"||c=="arguments")?Array.flatten(this[b]):this[b]); }return d;},hexToRgb:function(b){if(this.length!=3){return null;}var a=this.map(function(c){if(c.length==1){c+=c;}return c.toInt(16);});return(b)?a:"rgb("+a+")"; },rgbToHex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).
toString(16); b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});Function.implement({extend:function(a){for(var b in a){this[b]=a[b];}return this;},create:function(b){var a=this; b=b||{};return function(d){var c=b.arguments;c=(c!=undefined)?$splat(c):Array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c); }var e=function(){return a.apply(b.bind||null,c);};if(b.delay){ret...
...omplete"].contains(document.readyState))?b():arguments.callee.delay(50); })();}else{document.addEvent("DOMContentLoaded",b);}}})();var JSON=new Hash(this.JSON&&{stringify:JSON.stringify,parse:JSON.parse}).extend({$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(a){return JSON.$specialChars[a]||"\\u00"+Math.floor(a.charCodeAt()/16).
toString(16)+(a.charCodeAt()%16).
toString(16); },encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';case"array":return"["+String(b.map(JSON.encode).clean())+"]"; case"object":case"hash":var a=[];Hash.each(b,function(e,d){var c=JSON.encode(e);if(c){a.push(JSON.encode(d)+":"+c);}});return"{"+a+"}";case"number":case"boolean":return String(b); case f...
E4X for templating - Archive of obsolete content
enience of JavaScript 1.8 expression closures), the templates can function more dynamically, offering the power and readability of templating languages such as Smarty for PHP (though admittedly without the currently wider cross-browser support of XSLT or the strictly-XML approach of PHPTAL or Seethrough templating). ...
...g). Security and escaping function e (str) { if (typeof str === 'xml') {str = str.
toString();} return str; } function quot (s) { // useful for placing user input within inline JavaScript; may be combined with escape function above as well if (typeof s === 'string') { return s.replace(/"/g, '"').replace(/'/g, '''); } if (typeof s === 'xml') { return s.
toString().replace(/"/g, '"').replace(/'/g, '''); } return String(s).replace(/"/g, '"').replace(/'/g, '''); } Localization E4X works nicely with a simple utility for localizing strings of a properties file: // Localization function $S(msg, args){ //get localized message var STRS = Cc['@mozilla.org/intl/stringbundle;1'].getService(Ci.nsIStringBundleService). ...
...et = <></>; for (k in xmllist) { if (xmllist.hasOwnProperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).forEach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new XML(item); } else { var ser = (new XMLSerializer()).serialize
ToString(item); ret += new XML(ser); } }); return ret; } Example: var fruits = <fruits> <item>Pear</item> <item>Banana</item> <item>Grapes</item> </fruits>; alert( // Using a JavaScript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toXMLString() ); /* <output> <item>B...
Processing XML with E4X - Archive of obsolete content
ssion at once (e.g., <b {a}>.) After executing the above example, the variable languages references an XML object corresponding to the <languages> node in the XML document. ...
...} or, simply: if (languages.@type == 'agile') { ... } Working with XML objects XML objects provide a number of methods for inspecting and updating their contents. ...
...angs = languages.lang; XMLList provides a length() method which can be used to find the number of contained elements: alert(languages.lang.length()); Note that unlike JavaScript arrays length is a method, not a property, and must be called using length(). We can iterate through the matching elements like so: for (var i = 0; i < languages.lang.length(); i++) { alert(languages.lang[i].
toString()); } Here we are using identical syntax to that used to access numbered items in an array. Despite these similarities to regular arrays, XMLList does not support Array methods such as forEach, and Array generics such as Array.forEach() are not compatible with XMLList objects. We can also use the for each...in statement introduced in JavaScript 1.6 as part of JavaScript's E4X support: for e...
Arrays - Learn web development
array, and retrieving some items from it: myArray.length; myArray[0]; // the first item in the array myArray[1]; // the second item in the array myArray[myArray.length-1]; // the last item in the array You can also go the opposite way using the join() method. ...
...ng some items from it: myArray.length; myArray[0]; // the first item in the array myArray[1]; // the second item in the array myArray[myArray.length-1]; // the last item in the array You can also go the opposite way using the join() method. Try the following: let myNewString = myArray.join(','); myNewString; Another way of converting an array to a string is to use the
toString() method. ...
...]; // the last item in the array You can also go the opposite way using the join() method. Try the following: let myNewString = myArray.join(','); myNewString; Another way of converting an array to a string is to use the
toString() method.
toString() is arguably simpler than join() as it doesn't take a parameter, but more limiting. With join() you can specify different separators, whereas
toString() always uses a comma. (Try running Step 4 with a different character than a comma.) let dogNames = ['Rocket','Flash','Bella','Slugger']; dogNames.
toString(); // Rocket,Flash,Bella,Slugger Adding and removing array items We've not yet covered adding and removing array items -- let us look at this now. We'll use the myArray array we ended up with in the last section. If you've not already f...
Working with Svelte stores - Learn web development
have to convert from string to object when saving, and vice versa when we are loading the value from local storage. Create a new file called localStore.js, in your src directory. ...
...lStore = (key, initial) => { // receives the key of the local storage and an initial value const
toString = (value) => JSON.stringify(value, null, 2) // helper function const toObj = JSON.parse // helper function if (localStorage.getItem(key) === null) { // item not present in local storage localStorage.setItem(key,
toString(initial)) // initialize local storage with initial value } const saved = toObj(localStorage.getItem(key)) // convert to object const { subscribe, set, update } = writable(saved) // create the underlying writable store return { subscribe, set: (value) => { localStorage.setItem(key,
toString(value)) // save also to local stora...
..., and returns an object with three methods: subscribe(), set(), and update(). When we create a new localStore, we'll have to specify the key of the web storage and an initial value. We then check if the value exists in web storage and, if not, we create it. We use the localStorage.getItem(key) and localStorage.setItem(key, value) methods to read and write information to web storage, and the
toString() and toObj() (which uses JSON.parse()) helper functions to convert the values. Next, we convert the string content received from the web storage to an object, and save that object in our store. Finally, every time we update the contents of the store, we also update the web storage, with the value converted to a string. Notice that we only had to redefine the set() method, adding the ...
Mozilla DOM Hacking Guide
manifests, etc. Recompile. Nuke components.reg if you build optimized. Wonder at the beauty of DOMClassInfo. How to expose a new DOM object to JavaScript Let's now go a step further. Not only do we want to add a new interface to an object, but we also want to expose a completely new object to JavaScript. ...
... What there is to do Implement your object in C++. ...
...bject, its // value being the XPConnect wrapper for the Location object. *objp = obj; return NS_OK; } This is the first step. It is required to have the getter for .location work as well, but that's another story. The second step is to map .location to .location.href in nsWindowSH::SetProperty() if (str == sLocation_id) { // Setting the location property JSString *val = ::JS_Value
ToString(cx, *vp); NS_ENSURE_TRUE(val, NS_ERROR_UNEXPECTED); // Convert the value assigned to location (i.e. the url) to a JSString. nsCOMPtr<nsISupports> native; wrapper->GetNative(getter_AddRefs(native)); // Get the pointer to the content object that was wrapped. nsCOMPtr<nsIDOMWindow> window(do_QueryInterface(native)); NS_ENSURE_TRUE(window, NS_ERROR_UNEXPECTED); // QueryInterface to have a...
Tutorial: Embedding Rhino
ether. String s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } Evaluating a script The code Object result = cx.evaluateString(scope, s, "<cmd>", 1, null); uses the Context cx to evaluate a string. Evaluation of the script looks up variables in scope, and errors will be reported with the filename <cmd> and line number 1. Printing the result The code System.out.println(cx.
toString(result)); prints the result of evaluating the script (contained in the variable result). result could be a string, JavaScript object, or other values. The
toString method converts any JavaScript value to a string. Exiting the Context The code } finally { Context.exit(); } exits the Context. This removes the association between the Context and the current thread and is an essential clea...
...java RunScript3 "x = 7" x = 7 f is undefined or not a function. $ java RunScript3 "function f(a) { return a; }" x is not defined. ...
... Counter example The Counter example is a simple host object. We'll go through it method by method below. It's easy to try out new host object classes in the shell using its built-in defineClass function. We'll see ho...
NS_ConvertASCIItoUTF16
(const char LowerCaseEqualsLiteral(char Assign AssignASCII AssignLiteral(const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsAu
toString Data Members No public members. Methods Constructors void NS_ConvertASCIItoUTF16(const char*) - source Parameters char* aCString void NS_ConvertASCIItoUTF16(const char*, PRUint32) - source Parameters char* aCString PRUint32 aLength void NS_ConvertASCIItoUTF16(const nsACString_internal&) - source Parameters nsACString_internal& aCString operator= nsAu
toString& operato...
...rs No public members. ...
...tructors void NS_ConvertASCIItoUTF16(const char*) - source Parameters char* aCString void NS_ConvertASCIItoUTF16(const char*, PRUint32) - source Parameters char* aCString PRUint32 aLength void NS_ConvertASCIItoUTF16(const nsACString_internal&) - source Parameters nsACString_internal& aCString operator= nsAu
toString& operator=(const nsAu
toString&) - source Parameters nsAu
toString& str nsString& operator=(const nsString&) - source Parameters nsString& str nsAString_internal& operator=(PRUnichar) - source Parameters PRUnichar c nsAString_internal& operator=(const PRUnichar*) - source Parameters PRUnichar* data nsAString_internal& operator=(const nsAString_internal&) - source Parameters nsAString_internal& str nsAString_internal& operator=(const ns...
NS_ConvertUTF8toUTF16
(const char LowerCaseEqualsLiteral(char Assign AssignASCII AssignLiteral(const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsAu
toString Data Members No public members. Methods Constructors void NS_ConvertUTF8toUTF16(const char*) - source Parameters char* aCString void NS_ConvertUTF8toUTF16(const char*, PRUint32) - source Parameters char* aCString PRUint32 aLength void NS_ConvertUTF8toUTF16(const nsACString_internal&) - source Parameters nsACString_internal& aCString operator= nsAu
toString& operator=(...
...mbers No public members. ...
...onstructors void NS_ConvertUTF8toUTF16(const char*) - source Parameters char* aCString void NS_ConvertUTF8toUTF16(const char*, PRUint32) - source Parameters char* aCString PRUint32 aLength void NS_ConvertUTF8toUTF16(const nsACString_internal&) - source Parameters nsACString_internal& aCString operator= nsAu
toString& operator=(const nsAu
toString&) - source Parameters nsAu
toString& str nsString& operator=(const nsString&) - source Parameters nsString& str nsAString_internal& operator=(PRUnichar) - source Parameters PRUnichar c nsAString_internal& operator=(const PRUnichar*) - source Parameters PRUnichar* data nsAString_internal& operator=(const nsAString_internal&) - source Parameters nsAString_internal& str nsAString_internal& operator=(const ns...
nsIMsgIdentity
John Doe email AString User's e-mail address, i.e. john@doe.com replyTo AString Optional replyTo address, i.e. johnNOSPAM@doe.com organization AString Optional organization composeHtml ...
...of the attribute to set. value Value to set the attribute to. getIntAttribute() Getter for int attributes. ...
...Getter for int attributes. long getIntAttribute(in string name); Parameters name Name of the attribute to get. ...
nsISelection
Read only. anchorOffset long The offset within the (text) node where the selection begins. Read only. focusNode nsIDOMNode Returns the node in which the selection ends. Read only. focusOffset long The offset...
...n( in nsIDOMNode parentNode ); Parameters parentNode The parent of the children to be added to the selection. ...
... of the children to be added to the selection. selectionLanguageChange() Modifies the cursor Bidi level after a change in keyboard direction. ...
nsISelectionPrivate
EndPlaceHolderTransaction will give rise to reflow/refreshing view/scroll, and call times of nsTextFrame::GetPointFro...
... used by text frame when it is painting the selection. ...
... painting the selection. ...
nsIXmlRpcFault
ing it. extensions/xml-rpc/idl/nsIXmlRpcClient.idlScriptable An XML-RPC exception. XML-RPC server fault codes are returned wrapped in this; access it using nsIXPConnect.GetPendingException->data. ...
...d 1.5 / SeaMonkey 1.0) Method overview void init(in PRInt32 faultCode, in string faultSring); string
toString(); Attributes Attribute Type Description faultCode PRInt32 Read only. faultString string Read only. ...
...1.0) Method overview void init(in PRInt32 faultCode, in string faultSring); string
toString(); Attributes Attribute Type Description faultCode PRInt32 Read only. faultString string Read only. ...
DocumentOrShadowRoot.getSelection() - Web APIs
tInstance.getSelection() Parameters None. Returns A Selection object. Example function foo() { var selObj = document.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like Window.alert()), the object's
toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.
toString() is automatically called when it is passed to Window.alert(). However, attempting to use a JavaScript String property or method such as length or substr di...
... selectedText is a string (Selected text). Related objects You can call Window.getSelection(), which works identically to Document.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. ...
...g() is automatically called when it is passed to Window.alert(). However, attempting to use a JavaScript String property or method such as length or substr directly on a Selection object results in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its
toString() method directly: var selectedText = selObj.
toString(); selObj is a Selection object. selectedText is a string (Selected text). Related objects You can call Window.getSelection(), which works identically to Document.getSelection(). It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. HTMLInputElement.setSelectionRange()) could be used to work around this. Notice also the difference be...
URLSearchParams.set() - Web APIs
available in Web Workers. Syntax URLSearchParams.set(name, value) Parameters name The name of the parameter to set. value The value of the parameter to set. Return value Void. Examples Let's start with a simple example: let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); //Add a third parameter. params.set('baz', 3); params.
toString(); // "foo=1&bar=2&baz=3" Below is a real-life example demonstrating how to create a URL and set some search parameters. You can copy and paste the example in a code environment like Codepen, JSFiddle, or the multi-line JavaScript interpreter in Firefox. line #41: Comment out this line to stop dumping the search parameters to the console (debug). line #43: Dumps the generated object and...
...mping the search parameters to the console (debug). line #43: Dumps the generated object and it's string representation to the console (info). line #44: Tries to automatically open a new window/tab with the generated URL (when uncommented). ...
... Living Standard Initial definition. ...
Parsing and serializing XML - Developer guides
l, although differentiating has some practical benefits as well. Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is simply an alias for the Document interface. ...
...sing the XMLSerializer.serialize
ToString() method. Use the following approaches to serialize the contents of the XML document you created in the previous section. Serializing DOM trees to strings First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest. ...
...serialize the contents of the XML document you created in the previous section. Serializing DOM trees to strings First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest. To serialize the DOM tree doc into XML text, call XMLSerializer.serialize
ToString(): var oSerializer = new XMLSerializer(); var sXML = oSerializer.serialize
ToString(doc); Serializing HTML documents If the DOM you have is an HTML document, you can serialize using serialize
ToString(), but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants. var docHTML = document.documentElement.innerHTML; As a result, docH...
A re-introduction to JavaScript (JS tutorial) - JavaScript
y that was added with ECMAScript 5 is forEach(): ['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) { // Do something with currentValue or array[index] }); If you want to append an item to an array simply do it like this: a.push(item); Arrays come with a number of methods. See also the full documentation for array methods. Method name Description a.
toString() Returns a string with the
toString() of each element separated by commas. a.toLocaleString() Returns a string with the toLocaleString() of each element separated by commas. a.concat(item1[, item2[, ...[, itemN]]]) Returns a new array with the items added on to it. a.join(sep) Converts the array to a string -- with values delimited by the sep param ...
...g.prototype.reversed = function() { var r = ''; for (var i = this.length - 1; i >= 0; i--) { r += this[i]; } return r; }; s.reversed(); // nomiS Our new method even works on string literals! 'This can now be reversed'.reversed(); // desrever eb won nac sihT As mentioned before, the prototype forms part of a chain. ...
...string literals! 'This can now be reversed'.reversed(); // desrever eb won nac sihT As mentioned before, the prototype forms part of a chain. The root of that chain is Object.prototype, whose methods include
toString() -- it is this method that is called when you try to represent an object as a string. This is useful for debugging our Person objects: var s = new Person('Simon', 'Willison'); s.
toString(); // [object Object] Person.prototype.
toString = function() { return '<Person: ' + this.fullName() + '>'; } s.
toString(); // "<Person: Simon Willison>" Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the object that should be treated as 'this'. For example, here's a trivial implementation of new: function trivialNew(constructor...
Array.prototype.toLocaleString() - JavaScript
NOTE: In this case, we will use a comma var separator = ','; // 4. If len is zero, return the empty String. if (len === 0) { return ''; } // 5. Let firstElement be ? Get(A, "0"). var firstElement = a[0]; // 6. If firstElement is undefined or null, then // a.Let R be the empty String. // 7. Else, // a. Let R be ? //
ToString(? // Invoke( // firstElement, // "toLocaleString", // << locales, options >> // ) // ) var r = firstElement == null ? '' : firstElement.toLocaleString(locales, options); // 8. Let k be 1. var k = 1; // 9. Repeat, while k < len while (k < len) { // a. Let S be a String value pro...
...> // ) // ) var r = firstElement == null ? '' : firstElement.toLocaleString(locales, options); // 8. Let k be 1. var k = 1; // 9. Repeat, while k < len while (k < len) { // a. Let S be a String value produced by // concatenating R and separator. var s = r + separator; // b. ...
... while (k < len) { // a. Let S be a String value produced by // concatenating R and separator. var s = r + separator; // b. Let nextElement be ? Get(A,
ToString(k)). var nextElement = a[k]; // c. If nextElement is undefined or null, then // i. Let R be the empty String. // d. Else, // i. Let R be ? //
ToString(? // Invoke( // nextElement, // "toLocaleString", // << locales, options >> // ) // ) r = nextElement == null ? '' : nextElement.toLocaleString(locales, options); // e. Let R be a String value produced by // concatenating S and R. r = s + r; // f. Increase k b...
Array - JavaScript
d index number returns undefined. let arr = ['this is the first element', 'this is the second element', 'this is the last element'] console.log(arr[0]) // logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' Array elements are object properties in the same way that
toString is a property (to be specific, however,
toString() is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid: console.log(arr.0) // a syntax error There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notati...
...character.png') // a syntax error renderer['3d'].setTexture(model, 'character.png') // works properly In the 3d example, '3d' had to be quoted (because it begins with a digit). But it's also possible to quote the array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit
toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) Relationship between length and numerical properties A JavaScript array's length property and numerical properties are connected. Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into a...
...e element in this array satisfies the provided testing function. Array.prototype.sort() Sorts the elements of an array in place and returns the array. Array.prototype.splice() Adds and/or removes elements from an array. Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method. Array.prototype.
toString() Returns a string representing the array and its elements. Overrides the Object.prototype.
toString() method. Array.prototype.unshift() Adds one or more elements to the front of an array, and returns the new length of the array. Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. Array.prototype[@@iterator]() Returns a new Arra...
Date.prototype.toDateString() - JavaScript
stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.toDateString() Return value A string representing the date portion of the given Date object in human readable form in English. Description Date instances refer to a specific point in time. Calling
toString() will return the date formatted in a human readable form in English. In SpiderMonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method. The toDateString() method is especially useful becau...
...nkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method. ...
... toDateString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from
toString() for Date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines. Examples A basic usage of toDateString() var d = new Date(1993, 5, 28, 14, 39, 7); console.log(d.
toString()); // logs Mon Jun 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toDateString()); // logs Mon Jun 28 1993 Note: Month are 0-indexed when used as an argument of Date (thus 0 corresponds to January and 11 to December). Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toDateString' in that specification. ...
Date.prototype.toTimeString() - JavaScript
tored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.toTimeString() Return value A string representing the time portion of the given date in human readable form in American English. Description Date instances refer to a specific point in time. Calling
toString() will return the date formatted in a human readable form in American English. In SpiderMonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method. The toTimeString() method is especially use...
...nkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method. ...
...The toTimeString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from
toString() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines. Examples A basic usage of toTimeString() var d = new Date(1993, 6, 28, 14, 39, 7); console.log(d.
toString()); // Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toTimeString()); // 14:39:07 GMT-0600 (PDT) Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toTimeString' in that specification. ...
Function.prototype.bind() - JavaScript
be used in any production environment. Bound functions are automatically suitable for use with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. ...
...se with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. ...
... this.x = x; this.y = y; } Point.prototype.
toString = function() { return `${this.x},${this.y}`; }; const p = new Point(1, 2); p.
toString(); // '1,2' // not supported in the polyfill below, // works fine with native bind: const YAxisPoint = Point.bind(null, 0/*x*/); const emptyObj = {}; const YAxisPoint = Point.bind(emptyObj, 0/*x*/); const axisPoint = new YAxisPoint(5); axisPoint.
toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new YAxisPoint(17, 42) instanceof Point; // true Note that you need not do anything special to create a bound function for use with new. The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather ...
Object.keys() - JavaScript
g over the properties of the object manually. ...
...ally. ...
...s support in older environments that do not natively support it, copy the following snippet: // From /docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({
toString: null }).propertyIsEnumerable('
toString'), dontEnums = [ '
toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw new TypeError('Object.keys called on non-object'); ...
Symbol.prototype.description - JavaScript
like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. ...
...ll request. Description Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. It is different to Symbol.prototype.
toString() as it does not contain the enclosing "Symbol()" string. See the examples. ...
...property can be used to read that description. It is different to Symbol.prototype.
toString() as it does not contain the enclosing "Symbol()" string. See the examples. Examples Using description Symbol('desc').
toString(); // "Symbol(desc)" Symbol('desc').description; // "desc" Symbol('').description; // "" Symbol().description; // undefined // well-known symbols Symbol.iterator.
toString(); // "Symbol(Symbol.iterator)" Symbol.iterator.description; // "Symbol.iterator" // global symbols Symbol.for('foo').
toString(); // "Symbol(foo)" Symbol.for('foo').description; // "foo" Specifications Specification ECMAScript (ECMA-262)The definition of 'get Symbol.prototype.description' in that specification. ...
Symbol - JavaScript
that returns the index within a string that matches the regular expression. Used by String.prototype.search(). Symbol.split A method that splits a string at the indices that match a regular expression. Used by String.prototype.split(). Symbol.species A constructor function that is used to create derived objects. Symbol.toPrimitive A method converting an object to a primitive value. Symbol.
toStringTag A string value used for the default description of an object. Used by Object.prototype.
toString(). Symbol.unscopables An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object. Static methods Symbol.for(key) Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets crea...
...Symbol.keyFor(sym) Retrieves a shared symbol key from the global symbol registry for the given symbol. Instance properties Symbol.prototype.description A read-only string containing the description of the symbol. Instance methods Symbol.prototype.toSource() Returns a string containing the source of the Symbol object. Overrides the Object.prototype.toSource() method. Symbol.prototype.
toString() Returns a string containing the description of the Symbol. Overrides the Object.prototype.
toString() method. Symbol.prototype.valueOf() Returns the primitive value of the Symbol object. Overrides the Object.prototype.valueOf() method. Symbol.prototype[@@toPrimitive] Returns the primitive value of the Symbol object. Examples Using the typeof operator with symbols The typeof operator can...
...trying to convert a symbol to a number, a TypeError will be thrown (e.g. +sym or sym | 0). When using loose equality, Object(sym) == sym returns true. Symbol("foo") + "bar" throws a TypeError (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example. The "safer" String(sym) conversion works like a call to Symbol.prototype.
toString() with symbols, but note that new String(sym) will throw. Symbols and for...in iteration Symbols are not enumerable in for...in iterations. In addition, Object.getOwnPropertyNames() will not return symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these. let obj = {} obj[Symbol('a')] = 'a' obj[Symbol.for('b')] = 'b' obj['c'] = 'c' obj.d = 'd' for (let i in...
parseFloat() - JavaScript
urns a floating point number. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax parseFloat(string) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the
ToString abstract operation. Leading whitespace in this argument is ignored. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. Description parseFloat is a top-level function and not a method of any object. If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MIN...
...ny of the above characters), parseFloat returns NaN. parseFloat can also parse and return Infinity. parseFloat converts BigInt syntax to Numbers, losing precision. This happens because the trailing n character is discarded. Consider Number(value) for stricter parsing, which converts to NaN for arguments with invalid characters anywhere. ...
...ng objects if they have a
toString or valueOf method. The returned value is the same as if parseFloat had been called on the result of those methods. ...
Communicating using "port" - Archive of obsolete content
supplied to the page-mod in its onAttach function. By supplying a target for this function in the page-mod's constructor you can register to receive messages from the content script, and take a reference to the worker so as to emit messages to the content script. ...
...mber, boolean, null, array of JSON-serializable values, or an object whose property values are themselves JSON-serializable. This means you can't send functions, and if the object contains methods they won't be encoded. ...
url - Archive of obsolete content
the highest-level domain under which individual domains may be registered. Uses getPublicSuffix() internally. var urls = require("sdk/url"); console.log(urls.getTLD("http://www.bbc.co.uk/")); // "co.uk" console.log(urls.getTLD("https://developer.mozilla.org/")); // "org" Parameters url : string The URL, as a string. Returns string : The top-level domain for the URL. URL Methods
toString() Returns a string representation of the URL. Returns string : The URL as a string. toJSON() Returns a string representation of the URL. Returns string : The URL as a string. Properties scheme The name of the protocol in the URL, without the trailing ':'. Compare with protocol. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes...
...Add-ons?example=true&visible=yes#top"); console.log(url.protocol); // https: search If any parameters are present, a '?' followed by the parameters of the URL, as a string. Mirrors window.location.search. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes DataURL Methods
toString() Returns a string representation of the Data URL. If base64 is true, the data property is encoded using base-64 encoding. Returns string : The URL as a string. Properties mimeType The MIME type of the data. By default is an empty string. parameters An hashmap that contains the parameters of the Data URL. By default is an empty object. base64 Defines the encoding for the value in data p...
Miscellaneous - Archive of obsolete content
It also collapses consecutive whitespaces into a single whitespace, and returns at most 150 characters, making it id...
...To see what the postdata looks like before the request is even sent, use the 'http-on-modify-request' observer topic: observerService.addObserver(observer, 'http-on-modify-request', false); where "observer" is an object that has a method "observe": function obse...
Rosetta - Archive of obsolete content
First, you should declare a function which will translate an input plain-text written in C to an output plain-text written...
...mpiler() \u2013 not enough arguments"); } if (typeof fCompiler !== "function") { throw new TypeError("rosetta.appendCompiler() \u2013 second argument must be a function"); } if (!Array.isArray(vMimeTypes)) { oDicts[(vMimeTypes).
toString()] = fCompiler; return true; } for (var nIdx = 0; nIdx < vMimeTypes.length; nIdx++) { oDicts[(vMimeTypes[nIdx]).
toString()] = fCompiler; } return true; }; })(); Now, imagine you need a compiler for scripts written in C (MIME type: text/x-c). First, you should declare a function which will translate an input plain-text written in C to an output plain-text written in ECMAScript. Let us call this function createECMASrc() and let us associate it with the C MIME types: rosetta_c.js: A C compiler /* C Co...
Tabs - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no longer under active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! In this class you can find information about the tabs in your Firefox window. The namespace for this class is jetpack.tabs. blah(lengthstringfocusedstring
toStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring
toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady()when the inherited document is fully loaded. onFocus()changing the...
...tring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady()when the inherited document is fully loaded. onFocus()changing the focus of a tab. Methods open(urlstring)Opens a new tab in your browser with a defined url. urlURL to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstring
toStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring
toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady()when the inherited document is fully loaded. onFocus()ch...
Introduction - Archive of obsolete content
an XML document that reads <foo>2</foo>. You can also use brace notation on attributes of elements (their names or values). For example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different XML document: <foo bar="2">"hi"</foo>. Note, however, that XML elements can only have text as their value. What really happens with the {} notation is that the variables'
toString method is called, and the returned value is placed in the element. For instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object Object]</bar>. Use of inline functions in content Although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline: var a = 'foo'; ...
...OO25</bar>. See E4X for templating for more discussion on this usage. Serializing One of the most powerful tools of E4X is its ability to serialize an entire XML document (or portion thereof) into a string with one simple call to .toXMLString() var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); element1.toXMLString(); This will print <foo> <bar/> </foo> Calling
toString() will achieve the same effect in this case, though calling
toString() on an element with only text content will product the text content (e.g., <foo>abc</foo>.
toString(); will simply provide 'abc'). << PreviousNext >> ...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
.MIN_SAFE_INTEGER (Firefox 31) Number.isSafeInteger() (Firefox 32) Additions to the Object object Object.prototype.__proto__ has been standardized Object.is() (Firefox 22) Object.setPrototypeOf() (Firefox 31) Object.assign() (Firefox 34) Object.getOwnPropertySymbols() (Firefox 33) Additions to the Date object Date.prototype is an ordinary object (Firefox 41) generic Date.prototype.
toString (Firefox 41) Date.prototype[@@toPrimitive] (Firefox 44) New Promise object Promise (Firefox 24, enabled by default in Firefox 29) New Proxy object Proxy (Firefox 18) preventExtensions() trap (Firefox 22) isExtensible() trap (Firefox 31) getPrototypeOf() and setPrototypeOf() traps (Firefox 49) New Reflect object Reflect (Firefox 42) Additions to the RegExp object RegExp sti...
...(Firefox 24, enabled by default in Firefox 29) New Proxy object Proxy (Firefox 18) preventExtensions() trap (Firefox 22) isExtensible() trap (Firefox 31) getPrototypeOf() and setPrototypeOf() traps (Firefox 49) New Reflect object Reflect (Firefox 42) Additions to the RegExp object RegExp sticky (y) flag (Firefox 38) RegExp unicode (u) flag (Firefox 46) generic RegExp.prototype.
toString (Firefox 39) RegExp.prototype[@@match]() (Firefox 49) RegExp.prototype[@@replace]() (Firefox 49) RegExp.prototype[@@search]() (Firefox 49) RegExp.prototype[@@split]() (Firefox 49) get RegExp[@@species] (Firefox 49) Additions to the String object String.fromCodePoint() (Firefox 29) String.prototype.codePointAt() (Firefox 29) String.prototype.startsWith(), String.prototype.endsWith() (F...
JavaArray - Archive of obsolete content
the JavaArray is passed back to Java, the array is unwrapped and can be used by Java code. See the Core JavaScript 1.5 Guide for more information about data type conversions. In JavaScript 1.4 and later, the methods of java.lang.Object are inherited by JavaArray. Backward compatibility JavaScript 1.3 and earlier The methods of java.lang.Object are not inherited by JavaArray. In addition, the
toString method is inherited from the Object object and returns the following value: [object JavaArray] You must specify a class object, such as one returned by java.lang.Object.forName, for the componentType parameter of newInstance when you use this method to create an array. You cannot use a JavaClass object for the componentType parameter. Properties length: The number of elements in the Java arr...
...ject and returns the following value: [object JavaArray] You must specify a class object, such as one returned by java.lang.Object.forName, for the componentType parameter of newInstance when you use this method to create an array. You cannot use a JavaClass object for the componentType parameter. Properties length: The number of elements in the Java array represented by JavaArray. Methods
toString: In JavaScript 1.4, this method is overridden by the inherited method java.lang.Object.
toString. in JavaScript 1.3 and earlier, this method returns a string identifying the object as a JavaArray. In JavaScript 1.4 and later, JavaArray also inherits methods from the Java array superclass, java.lang.Object. Examples Example: Instantiating a JavaArray in JavaScript In this example, the JavaArray...
Object prototypes - Learn web development
Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']); If you type "person1." into your JavaScript console, you should see the browser try to auto-complete this with the member names available on this object: In this list, you will see the members defined on person1's constructor -- Person() -- name, age, gender, interests, bio, and greeting. You will however also see some other members --
toString, valueOf, etc -- these are defined on person1's prototype object's prototype object, which is Object.prototype. What happens if you call a method on person1, which is actually defined on Object.prototype? For example: person1.valueOf() valueOf() returns the value of the object it is called on. In this case, what happens is: The browser initially checks to see if the person1 object has a v...
...erited ones are the ones defined on the prototype property (you could call it a sub-namespace) -- that is, the ones that begin with Object.prototype., and not the ones that begin with just Object. The prototype property's value is an object, which is basically a bucket for storing properties and methods that we want to be inherited by objects further down the prototype chain. So Object.prototype.
toString(), Object.prototype.valueOf(), etc., are available to any object types that inherit from Object.prototype, including new object instances created from the Person() constructor. Object.is(), Object.keys(), and other members not defined inside the prototype bucket are not inherited by object instances or object types that inherit from Object.prototype. They are methods/properties available just on...
Debugging on Windows
VC++ 6.0: C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin\AUTOEXP.DAT VC++ 7.0: C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\Debugger\AUTOEXP.DAT The file has information about the format in the beginning, and after a little practice you should be well on your way. ...
...v98\Bin\AUTOEXP.DAT VC++ 7.0: C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\Debugger\AUTOEXP.DAT The file has information about the format in the beginning, and after a little practice you should be well on your way. Here are some entries that will make your life easier: ;; Mozilla (1.7beta and later) nsAu
toString=<mData,su> nsString=<mData,su> nsCString=<mData,s> nsCAu
toString=<mData,s> nsRect=x=<x,d> y=<y,d> width=<width,d>; height=<height,d> nsStaticAtomWrapper=<mStaticAtom->mString,s> nsIAtom=<mString,su> ; the following are not necessary in vc8 nsCOMPtr<*>=<mRawPtr,x> nsRefPtr=<mRawPtr,x> nsAutoPtr=<mRawPtr,x> After you have made the changes and saved the file, you will need to restart Visual C++ for the changes to take effect. For XPCOM Strings (the "external" ...
Dict.jsm
Note: Any String you pass will be assumed to be JSON. Method overview Dict copy(); boolean del(String aKey); Object get(String aKey, [optional] Object aDefault); boolean has(String aKey); Array listitems(); Array listkeys(); Array listvalues(); void set(String aKey, Object aValue); String toJSON(); String
toString(); Properties Attribute Type Description count Number The number of items in the dictionary. items Iterator Returns an iterator over all of the items in the dictionary; each item is returned as a pair (a two-element array) with the first element being the key and the second being the value. Note: The order in which items are returned ...
...ionary if necessary. void set( String aKey, Object aValue ); Parameters aKey The key whose value is to be set. aValue The value to assign to the given key. toJSON() Returns a JSON String representation of the dictionary. String toJSON(); Parameters None. Return value A JSON String representation of the dictionary's key/value pairs. This will be "{}" for an empty dictionary.
toString() Returns a string representation of the dictionary. String
toString(); Parameters None. Return value A string representation of the dictionary's key/value pairs. This will be "{}" for an empty dictionary. Examples Creating and populating a dictionary This example creates a new dictionary and adds some key/value pairs to it. var myDict = new Dict(); myDict.set("name", "John Smith"); my...
NetUtil.jsm
s methods. Method overview nsIAsyncStreamCopier asyncCopy(nsIInputStream aSource, nsIOutputStream aSink, [optional] aCallback) void asyncFetch(aSource, aCallback) nsIChannel newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] nsIURI aBaseURI) nsIURI newURI(aTarget, [optional] aOriginCharset, [optional] nsIURI aBaseURI) String readInputStream
ToString(aInputStream, aCount, aOptions) Attributes Attribute Type Description ioService nsIIOService Returns a reference to nsIIOService. Methods asyncCopy() The asyncCopy() method performs a simple asynchronous copy of data from a source input stream to a destination output stream. Both streams are automatically closed when the copy operation is completed. ...
...ional character set for the URI. Defaults to UTF-8 if not provided. aBaseURI The base URI for the spec, specified as an nsIURI. Return value Returns the nsIURI object representing the specified target. Exceptions thrown This method throws an exception with the message "Must have a non-null string spec or nsIFile object" and result code NS_ERROR_INVALID_ARG if aSpec is null. readInputStream
ToString() Reads a given number of bytes from an input stream, returning a string containing those bytes. This works even if some of those bytes are zeros, instead of terminating the string at the first zero byte. String readInputStream
ToString( aInputStream, aCount, aOptions ); Parameters aInputStream The input stream from which to read the data. aCount The number of bytes to read from th...
SourceMap.jsm
for this source map being created. The mapping object should have the following properties: generated: An object with the generated line and column positions. original: An object with the original line and column positions. source: The original source file (relative to the sourceRoot). name: An optional original token name for this mapping. SourceMapGenerator.prototype.
toString() Renders the source map being generated to a string. SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputtin...
...s the separator between each of this source node's children. sep: The separator. SourceNode.prototype.replaceRight(pattern, replacement) Call String.prototype.replace on the very rightmost source snippet. Useful for trimming whitespace from the end of a source node, etc. pattern: The pattern to replace. replacement: The thing to replace the pattern with. SourceNode.prototype.
toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. SourceNode.prototype.
toStringWithSourceMap(startOfSourceMap) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same...
Enc Dec MAC Output Public Key as CSR
ne NS_CERTREQ_HEADER "-----BEGIN NEW CERTIFICATE REQUEST-----" #define NS_CERTREQ_TRAILER "-----END NEW CERTIFICATE REQUEST-----" typedef enum { GEN_CSR, ENCRYPT, DECRYPT, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4, PUBKEY = 5, LAB = 6 } HeaderType; /* This is conditionalized because PORT_Error
ToString was introduced with nss 3.13. * Though PR_Error
ToString was available, support for it in nss wasn't. * FIXME: samples should determine the version of nss that's available and refuse * to run if not 3.13 or higher. */ #ifndef PORT_Error
ToString #ifndef SEC_ERROR_BASE #define SEC_ERROR_BASE (-0x2000) #define PORT_Error
ToString(err) PR_Error
ToString((err), PR_LANGUAGE_I_...
... mechanism; SECOidTag algtag; PK11RSAGenParams rsaparams; void *params; SECKEYPrivateKey *privKey = NULL; SECStatus rv; unsigned char randbuf[BLOCKSIZE + 1]; rv = GenerateRandom(randbuf, BLOCKSIZE); if (rv != SECSuccess) { fprintf(stderr, "Error while generating the random numbers : %s\n", PORT_Error
ToString(rv)); goto cleanup; } PK11_RandomUpdate(randbuf, BLOCKSIZE); switch (keytype) { case rsaKey: rsaparams.keySizeInBits = size; rsaparams.pe = publicExponent; mechanism = CKM_RSA_PKCS_KEY_PAIR_GEN; algtag = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION; params = ...
JS::OrdinaryToPrimitive
ype The type of converted value. vp JS::MutableHandleValue Out parameter. On success, *vp receives the converted value. Description JS::OrdinaryToPrimitive converts a JavaScript object to a specified type value, by the algorithm specified in ES6 draft rev 28 (2014 Oct 14) 7.1.1, second algorithm. Most users should not call this -- use JS::ToNumber, JS::ToBoolean, or JS::
ToString instead. This should only be called from custom convert hooks. It implements the default conversion behavior shared by most objects in JS, so it's useful as a fallback. On success, JS::OrdinaryToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS::OrdinaryToPrimitive JS::...
... called from custom convert hooks. ...
JS::Value
The different representati...
...ndefined() returns true if the value is either null or undefined. val.isGCThing() returns true if a JS value has a type that is subject to garbage collection. The are two major issues to be aware of when using JS::Value. JS::Value is not inherently type-safe It is an error to call any accessor method on a value of a non-matching type: val.toInt32() must only be called if val.isInt32(), val.
toString() must only be called if val.isString(), and so on. In particular, note that it is an error to call val.toObject() when val.isNull(). The now-deprecated jsval methods allowed JSVAL_TO_OBJECT(val) when JSVAL_IS_NULL(val), but this was a source of constant bugs. val.toObject() is only permitted when val.isObject(). An assertion is thrown in the case that the type is not correct (val.isX() is calle...
JSAutoByteString
AutoByteString instance is initialized with JSAutoByteString bytes; style, it does not own any string. You can call some methods to take ownership of other string. Note that the JS_EncodeString call in constructor and some encode* methods may fail and get NULL. So ensure the string is returned by operator!() before using ptr() method. ...
...*/ /* when leaving this scope, the string returned by JS_EncodeStringToUTF8 is freed. ...
JSObjectOps.defaultValue
escription The JSObjectOps.defaultValue callback corresponds to the [[DefaultValue]] method defined in ECMA 262-3 ?8.6.2.6. Many expressions in the ECMAScript language, such as a+b, involve implicit conversion of the operands using [[DefaultValue]]. The default [[DefaultValue]] behavior for ordinary objects is as described in ES5 ?8.12.8. It calls the JavaScript methods obj.valueOf() and/or obj.
toString(). Provide a custom JSObjectOps.defaultValue callback to implement customized [[DefaultValue]] behavior. The JSClass.convert callback should convert obj to the given type, returning JS_TRUE with the resulting value in *vp on success, and returning JS_FALSE on error or exception. On success, *vp must be a primitive value: per ES5 ?8.12.8, every object "must ensure that its [[DefaultValue]] intern...
... ...
JSVersion
The values of the JSVersion enumerated type stand for particular versions of the JavaScript run-time. The functions JS_GetVersion, JS_SetVersion, JS_StringToVersion, and JS_Version
ToString use these values. Description The JSVersion enumerated type includes the following values. Each version has a name, which is a string used by JS_StringToVersion and JS_Version
ToString. Enumeration Value Meaning Name JSVERSION_1_0Obsolete since JSAPI 24 100 JavaScript 1.0 "1.0" JSVERSION_1_1Obsolete since JSAPI 24 110 JavaScript 1.1 "1.1" JSVERSION_1_2Obsolete since JSAPI 24 120 JavaScript 1.2 "1.2" JSVERSION_1_3Obsolete since JSAPI 24 130 JavaScript 1.3 "1.3" JSVERSION_1_4Obsolete since JSAPI 24 14...
...2 Edition 5 "ECMAv5" JSVERSION_DEFAULT 0 Latest JavaScript version, but omitting web-incompatible extensions "default" JSVERSION_UNKNOWN -1 Unknown JavaScript version NULL JSVERSION_LATEST JSVERSION_ECMA_5 Latest JavaScript version NULL See Also MXR ID Search for JSVersion JS_GetVersion JS_SetVersion JS_StringToVersion JS_Version
ToString bug 824312 ...
SpiderMonkey 31
This is performed by calling the new JS_Init method before creating any runtimes or contexts and before compiling, evaluating, or executing any JS script. Once this method has been successfully called, it's okay to call...
... This is performed by calling the new JS_Init method before creating any runtimes or contexts and before compiling, evaluating, or executing any JS script. Once this method has been successfully called, it's okay to call JS_NewRuntime and all the...
Places Developer Guide
/browser/nav-history-service;1']. getService(Components.interfaces.nsPIPlacesDatabase).DBConnection; } And then to get the a redirected visit_id from another visit_id: function getFromVisit(visit_id) { var sql = <cdata><![CDATA[ SELECT from_visit FROM moz_places, moz_historyvisits WHERE moz_historyvisits.id = :visit_id AND moz_places.id = moz_historyvisits.place_id; ]]></cdata>.
toString(); var sql_stmt = getPlacesDbConn.createStatement(sql); sql_stmt.params.visit_id = visit_id; var from_visit; try { // Here we can't use the "executeAsync" method since have to return a // result right-away. while (sql_stmt.executeStep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } Note: The <cdata><!
...PlacesDbConn.createStatement(sql); sql_stmt.params.visit_id = visit_id; var from_visit; try { // Here we can't use the "executeAsync" method since have to return a // result right-away. while (sql_stmt.executeStep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } Note: The <cdata><![CDATA[ xxx ]]></cdata>.
toString() notation is E4X and it makes possible to write multi-line strings in JavaScript. This is very useful when writing long SQL statements. Searching History Queries are executed through the history service. The example below shows how to search through browser history, and to iterate over the results. var history = Cc["@mozilla.org/browser/nav-history-service;1"] .getService(Ci.nsINav...
Components.Constructor
given, that argument is the contract ID of the XPCOM component to create. The component is then returned immediately, with only the base interface nsISupports available on it; you must call nsISupports.QueryInterface() on it to call methods on the object. ...
...The arguments used with the initialization method are the arguments passed to the Compone...
NS_ConvertUTF16toUTF8
Methods Constructors void NS_ConvertUTF16toUTF8(const PRUnichar*) - source A helper class that converts a UTF-16 string to UTF-8 Parameters PRUnichar* aString void NS_ConvertUTF16toUTF8(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aString PRUint32 aLength void NS_ConvertUTF16toUTF8(const nsAString_internal&) - source Parameters ...
...structors void NS_ConvertUTF16toUTF8(const PRUnichar*) - source A helper class that converts a UTF-16 string to UTF-8 Parameters PRUnichar* aString void NS_ConvertUTF16toUTF8(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aString PRUint32 aLength void NS_ConvertUTF16toUTF8(const nsAString_internal&) - source Parameters nsAString_internal& aString operator= nsCAu
toString& operator=(const nsCAu
toString&) - source Parameters nsCAu
toString& str nsCString& operator=(const nsCString&) - source Parameters nsCString& str nsACString_internal& operator=(char) - source Parameters char c nsACString_internal& operator=(const char*) - source Parameters char* data nsACString_internal& operator=(const nsACString_internal&) - source Parameters nsACStri...
NS_LossyConvertUTF16toASCII
Methods Constructors void NS_LossyConvertUTF16toASCII(const PRUnichar*) - source A helper class that converts a UTF-16 string to ASCII in a lossy manner Parameters PRUnichar* aString void NS_LossyConvertUTF16toASCII(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aString PRUint32 aLength void NS_LossyConvertUTF16toASCII(const nsAStrin...
...6toASCII(const PRUnichar*) - source A helper class that converts a UTF-16 string to ASCII in a lossy manner Parameters PRUnichar* aString void NS_LossyConvertUTF16toASCII(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aString PRUint32 aLength void NS_LossyConvertUTF16toASCII(const nsAString_internal&) - source Parameters nsAString_internal& aString operator= nsCAu
toString& operator=(const nsCAu
toString&) - source Parameters nsCAu
toString& str nsCString& operator=(const nsCString&) - source Parameters nsCString& str nsACString_internal& operator=(char) - source Parameters char c nsACString_internal& operator=(const char*) - source Parameters char* data nsACString_internal& operator=(const nsACString_internal&) - source Parameters nsACStri...
nsICategoryManager
var categoryManager = Components.classes["@mozilla.org/categorymanager;1"] .getService(Components.interfaces.nsICategoryManager); var enumerator = categ...
...The second portion of this snippet disables plugins from loading in the future, it does not user the category manager but it is included for completness of the exampl...
nsICryptoHash
var s = Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); // s now contains your hash in hex This gives 5eb63bbbe01eeed093cb22bb8f5acdc3 for the hash value. This example, while simple, shows most of the functionality of the interface. The first thing to note is that when you call the init() method you must ...
...var s = Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); // s now contains your hash in hex: should be // 5eb63bbbe01eeed093cb22bb8f5acdc3 See also Firefox 1.5 ...
nsIDOMSerializer
changed in Gecko 1.7 Implemented by: @mozilla.org/xmlextras/xmlserializer;1. To create an instance, use: var domSerializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createInstance(Components.interfaces.nsIDOMSerializer); Method overview void serializeToStream(in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); AString serialize
ToString(in nsIDOMNode root); Methods serializeToStream() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. void serializeToStream( in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. stream The byte stream to wh...
...n nsIOutputStream stream, in AUTF8String charset ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. stream The byte stream to which the subtree is serialized. charset The name of the character set to use for the encoding to a byte stream. If this string is empty and root is a document, the document's character set will be used. serialize
ToString() The subtree rooted by the specified element is serialized to a string. AString serialize
ToString( in nsIDOMNode root ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. Return value The serialized subtree in the form of a Unicode string. ...
nsIEditor
splitNode(in nsIDOMNode existingRightNode, in long offset, out nsIDOMNode newLeftNode); void joinNodes(in nsIDOMNode leftNode, in nsIDOMNode rightNode, in nsIDOMNode parent); void deleteNode(in nsIDOMNode child); void markNodeDirty(in nsIDOMNode node); Direction Controller void switchTextDirection(); Output Methods AString output
ToString(in AString formatType, in unsigned long flags); Example: // flags are declared in base/public/nsIDocumentEncoder.idl // OutputSelectionOnly = 1, OutputFormatted = 2, // OutputRaw = 4, OutputBodyOnly = 8, // OutputPreformatted = 16, OutputWrap = 32, // OutputFormatFlowed = 64, OutputAbsoluteLinks = 258, // OutputEncodeW3CEntities = 256, OutputCRLin...
...putFormatFlowed = 64, OutputAbsoluteLinks = 258, // OutputEncodeW3CEntities = 256, OutputCRLineBreak = 512, // OutputLFLineBreak = 1024, OutputNoScriptContent = 2048, // OutputNoFramesContent = 4096, OutputNoFormattingInPre = 8192, // OutputEncodeBasicEntities=16384, OutputEncodeLatin1Entities=32768, // OutputEncodeHTMLEntities=65536, OutputPersistNBSP=131072 editorAPI.output
ToString('text/html', 2); editorAPI.output
ToString('text/plain', 4); // output the body tag, body children and the html end tag (</html>). // tag name are in lower case with <br>. editorAPI.output
ToString('text/html', 8); // XML: all in xml with _moz_dirty="" in new tags, HTML tags are in upper case // application/xhtml+xml format do the same editorAPI.output
ToString('text/xml', 2); // the body is not ...
nsIException
There is no unambiguous indicator for unknown. Read only. data nsISupports Arbitary data for the implementation. Read only. filename string Filename location. This is the location that caused the error, which may or may not be a source file location. ...
...wn. Read only. location nsIStackFrame A stack trace, if available. Read only. message string A custom message set by the thrower. [binaryname(MessageMoz)] Read only. name string The name of the error code (A string representation of result) Read only. result nsresult The nsresult associated with this exception. Read only. Methods
toString() A generic formatter - make it suitable to print, etc. string
toString(); Parameters None. Return value A string suitable for output. ...
nsIHttpChannelInternal
this to true to notify the channel that it is open on behalf of a download. documentURI nsIURI An HTTP channel can own a reference to the document URI. forceAllowThirdPartyCookie boolean Force relevant cookies to be sent with this load even if normally they would not be. localAddress AUTF8String The local IP address to which the channel is bound, in the same format produced by PR_NetAddr
ToString(). This may be either an IPv4 or IPv6 address. Note: If Network Address Translation (NAT) is in effect, this may not be the same address the remote host thinks it is talking to. This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. ...
...hannel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Read only. proxyInfo nsIProxyInfo Get the proxy info in use by the channel. Read only. Obsolete since Gecko 1.9 remoteAddress AUTF8String The IP address of the remote host to which this channel is bound, in the same format produced by PR_NetAddr
ToString(). This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Read only. remotePort PRInt32 The remote port number to which the channel is bound. This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpo...
nsIJSID
unnamed JSID. An unnamed JSID also results when you implement a function that is passed an nsIIDRef parameter, such as QueryInterface(). Note that for these cases of JSID the specified class or interface must exist and be scriptable. Method overview boolean equals(in nsIJSID other); const nsID* getID(); Violates the XPCOM interface guidelines void initialize(in string idString); string
toString(); Attributes Attribute Type Description id nsIDPtr Read only. Native code only! Obsolete since Gecko 1.9 The internal nsID. name string Read only. The name of the JSID, if it was set. number string Read only. The string representation of the internal nsID. valid boolean Read only. Returns true if the JSID has been initialised. Methods equals() This method determines if this nsIJ...
...otherwise false. Violates the XPCOM interface guidelines getID() const nsID* getID(); Parameters None. Return value A pointer to the internal nsID structure. initialize() Initializes the JSID. void initialize( in string idString ); Parameters idString The number to initialize the JSID, in string format, e.g. {00000000-0000-0000-c000-000000000046}. A JSID can only be initialized once.
toString() This methods returns a string representation of the object. string
toString(); Parameters None. Return value The name of the JSID if it has one, otherwise the string representation of its nsID. ...
nsIMsgIncomingServer
biffMinutes long biffState unsigned long canBeDefaultServer boolean Read only. canCompactFoldersOnServer boolean Read only. canCreateFoldersOnServer boolean canDelete boolean can this server be removed from the account manager? fo...
...ue ); Parameters attr Missing Description value Missing Description Exceptions thrown Missing Exception Missing Description shutdown() void shutdown(); Parameters None. Exceptions thrown Missing Exception Missing Description storePassword() logon succeeded - persist password, if user chooses. void storePassword(); Parameters None. Exceptions thrown Missing Exception Missing Description
toString() AString
toString(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description writeToFolderCache() void writeToFolderCache( in nsIMsgFolderCache folderCache ); Parameters folderCache Missing Description Exceptions thrown Missing Exception Missing Description Remarks See also ...
nsIPrefLocalizedString
dentifier to distinguish between requests for normal wide strings nsISupportsString) and 'localized' wide strings, which get their default values from properites files. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void setDataWithLength(in unsigned long length, [size_is(length)] in wstring data); wstring
toString(); Attributes Attribute Type Description data wstring Provides access to string data stored in this property. Methods setDataWithLength() Used to set the contents of this object. void setDataWithLength( in unsigned long length, [size_is(length)] in wstring data ); Parameters length The length of the string. This value should not include spac...
... of this object. void setDataWithLength( in unsigned long length, [size_is(length)] in wstring data ); Parameters length The length of the string. This value should not include space for the null terminator, nor should it account for the size of a character. It should only be the number of characters for which there is space in the string. data The string data to be stored.
toString() Used to retrieve the contents of this object into a wide string. Note: This makes a copy of the string argument passed in. wstring
toString(); Parameters None. Return value Returns wstring - The string containing the data stored within this object. ...
nsIScriptError
Read only. columnNumber PRUint32 The column number where the error occurred. This is used to draw the arrow pointing to the problem character. Read only. errorMessage AString The error m...
... to the problem character. flags One of the script error Flag constants category A string indicating what kind of code caused the message. There are quite a few category strings and they aren't listed in a single place, so you may need to search the Firefox code to find the one you want. See Categories for a partial list. innerWindowID The ID of the inner window associated with the error.
toString() Outputs a string representing the error message described by the object. AUTF8String
toString(); Parameters None. Return value A string representing the error message described by the nsIScriptError object. Examples Logging a message with additional information In this example nsIScriptError, which implements nsIConsoleMessage, is used to log information to the console including infor...
nsIStackFrame
filename string Filename location. This is the location that caused the error, which may or may not be a source file location. For example, standard language errors would generally have the same location as their top stack entry. File parsers may put the location of the file they were parsing, and so forth. null indicates "no data" Read only. ...
...tants. Read only. lineNumber PRInt32 Valid line numbers begin at '1'. '0' indicates unknown. Read only. name string The name of the function at this point in the stack. Read only. sourceLine string The location of this function in filename Read only. Example To output the stack at a particular location: var s = Components.stack; while(s) { console.log(s.name); s = s.caller; } Methods
toString() A generic formatter - make it suitable to print, and so forth. string
toString(); Parameters None. Return value A string suitable for output. See also jsdIStackFrame ...
Working with ArrayBuffers
uffer; // buffer is a ArrayBuffer // incomingBuffer is a TypedArray var imageData2 = context.createImageData(w, h); imageData2.data.set(incomingBuffer); Further, if you have a byte array pixelBuffer, and you need to create ImageData from it. The data property holds an array of bytes. We start with the following: // pixelBuffer is a pointer to a RGBA pixel buffer of 400x400 image. pixelBuffer.
toString(); // "ctypes.uint8_t.ptr(ctypes.UInt64("0x352e0000"))" var imgWidth = 400; var imgHeight = 400; var myImgDat = new ImageData(imgWidth, imgHeight); Method 1: Passing ArrayType CData to Uint8ClampedArray.prototype.set One method is to get into a js-ctypes array, and then set it into the ImageData, as illustrated by the following code example. // Cast pointer to array, to pass to Uint8ClampedA...
... is to get into a js-ctypes array, and then set it into the ImageData, as illustrated by the following code example. // Cast pointer to array, to pass to Uint8ClampedArray.prototype.set. var casted = ctypes.cast(pixelBuffer.address(), ctypes.uint8_t.array(myImgData.data.length).ptr).contents; // myImgDat.data.length is imgWidth * imgHeight * 4 because per pixel there is r, g, b, a numbers casted.
toString(); // "ctypes.uint8_t.array(640000)([45, 66, 135, 255, 99, 86, 55, 255, .......... ])" myImgDat.data.set(casted); The ctypes.cast takes a couple of milliseconds, however, the myImgDat.data.set takes up to 800ms for a size of 52,428,800 (which is image size of 1280 x 1024 pixels). So, for the size of 640,000 it takes about 98ms. Method 2: Manually Handled Another strategy is to handle it manua...
Using js-ctypes
:('); } for (var cfstr in myCFStrs) { if (myCFStrs.hasOwnProperty(cfstr)) { var rez_CFRelease = CFRelease(myCFStrs[cfstr]); // ret...
...led the equivalent of the "StandardAlert Carbon function" for 64bit OSX from JavaScript!') }; var rez = CFUserNotificationDisplayNotice(0, kCFUserNotificationCautionAlertLevel, null, null, null, myCFStrs.head, myCFStrs.body, null); console.info('rez:', rez, rez.
toString(), uneval(rez)); // CFUserNotificationDisplayNotice does not block till user clicks dialog, it will return immediately if (rez.
toString() == '0') { console.log('Notification was succesfully shown!!'); } else { console.error('Failed to show notification... :('); } for (var cfstr in myCFStrs) { if (myCFStrs.hasOwnProperty(cfstr)) { var rez_CFRelease = CFRelease(myCFStrs[cfstr]); // returns void } } libcf.close(); Calling LibC routines on Linux/POSIX This example demonstrates how to use ctypes to call a libc function...
ArrayType
ting the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String
toString() ArrayType CData Syntax CData sized_arraytype(); CData unsized_arraytype(length); sized_arraytype and unsized_arraytype are ArrayType CType. Parameters length The number of entries the array type should be able to contain. Only for unsized ArrayType. Return value A CData representing the newly allocated array. Exceptions thrown TypeError length is not provided for unsized ...
... ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. ArrayType CData Method_overview CData addressOfElement(idx) Methods inherited from CData CData address() String toSource() String
toString() ArrayType CData Methods addressOfElement() Returns a new CData object of the appropriate pointer type, whose value points to the specified array element on which the method was called. CData addressOfElement( idx ); Parameters idx A numeric value indicating the offset into the array of the element just to return a pointer. If this value isn't a valid JavaScript number that's a...
CType
de access to 64-bit integer values, which JavaScript doesn't currently support. PointerType These represent pointers to data in memory. FunctionType These represent callable C functions. StructType These represent C structures. ArrayType These represent C arrays. Method overview Methods available on all CType objects CType array([n]) String toSource() String
toString() Properties Properties of all CType objects These properties are available on all CType objects. Property Type Description name String The type's name. Read only. For primitive types, this is just the name of the corresponding C type. For structure and opaque pointer types, this is simply the string that was passed to the constructor. For other f...
...this type". This is the same as calling ctypes.ArrayType(the_type[, n]). toSource() Returns a JavaScript expression that evaluates to a CType describing the same C type as this object. String toSource(); Parameters None. Return value A JavaScript expression that evaluates to a CType describing the same C type as this object. Example ctypes.uint32_t.toSource() returns "ctypes.uint32_t".
toString() Returns a string identifying the type. The format of this string is "type " + name. String
toString(); Parameters None. Return value A string identifying the data type. See Also ArrayType FunctionType PointerType StructType Type conversion ...
Int64
is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. Method overview Number compare(a, b); Number hi(a); Int64 join(high, low); Number lo(a); String toSource(); String
toString([radix]); Methods compare() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is: -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either signed or unsigned). hi() R...
...alues merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a JavaScript number with an integral value. toSource() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers.
toString() Returns a string representation of the object's numeric value. String
toString( [radix] ); Parameters radix Optional The radix (base) to use when constructing the string. If you don't specify a radix, base 10 is used. Return value A string representation of the value in the specified radix. This string consists of a leading minus sign, if the value was negative, followed by one or ...
PointerType
ting the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String
toString() PointerType CData Syntax CData pointertype(); pointertype is PointerType CType. Return value A CData representing the newly allocated pointer. PointerType CData Properties Property Type Description contents CData Reading this property returns a CData object referring to the pointed-to contents of the object. Writing to this value writes the C conversi...
...his is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. PointerType CData Method_overview bool isNull() Methods inherited from CData CData address() String toSource() String
toString() PointerType CData Methods isNull() Determines whether or not the pointer's value is null. bool isNull(); Parameters None. Return value true if the pointer's value is null, otherwise false. See Also CType CData Type conversion ...
StructType
this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview define(fields) Methods inherited from CType CType array([n]) String toSource() String
toString() Methods define() Defines a previously declared opaque type's fields. This lets you convert an opaque structure type into a defined structure type. define( fields ); Parameters fields A field specification, as described above. StructType CData Syntax CData structtype(); structtype is StructType CType. Return value A CData representing the newly allocated struct. Excepti...
... ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. StructType CData Method_overview CData addressOfField(name) Methods inherited from CData CData address() String toSource() String
toString() StructType CData Methods addressOfField() Returns a new CData object of the appropriate pointer type, whose value points to the specified field of the structure on which the method was called. See Working with strings for more information on how to convert strings. CData addressOfField( name ); Parameters name The name of the field whose address is to be returned. Return val...
UInt64
s incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. Method overview Number compare(a, b); Number hi(a); UInt64 join(high, low); Number lo(a); String toSource(); String
toString([radix]); Methods compare() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either signed or unsigned). hi() Retur...
...s merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a JavaScript number with an integral value. toSource() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers.
toString() Returns a string representation of the object's numeric value. String
toString( [radix] ); Parameters radix Optional The radix (base) to use when constructing the string. If you don't specify a radix, base 10 is used. Return value A string representation of the value in the specified radix. This string consists of a leading minus sign, if the value was negative, followed by one or ...
Background Tasks API - Web APIs
he log for each task. In your own application, you'd replace this code with whatever task it is you wish to perform during idle time. Just remember that anything you want to do that changes the DOM needs to be handled through requestAnimationFrame(). function logTaskHandler(data) { log("<strong>Running task #" + currentTaskNumber + "</strong>"); for (i=0; i<data.count; i+=1) { log((i+1).
toString() + ". " + data.text); } } The main program Everything is triggered when the user clicks the Start button, which causes the decodeTechnoStuff() function to be called. The getRandomIntInclusive() method comes from the examples for Math.random(); we'll just link to it below but it needs to be included here for the example to work. function getRandomIntInclusive(min, max) { min = Math.ceil...
... min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function decodeTechnoStuff() { totalTaskCount = 0; currentTaskNumber = 0; updateDisplay(); let n = getRandomIntInclusive(100, 200); for (i=0; i<n; i++) { let taskData = { count: getRandomIntInclusive(75, 150), text: "This text is from task number " + (i+1).
toString() + " of " + n }; enqueueTask(logTaskHandler, taskData); } } document.getElementById("startButton").addEventListener("click", decodeTechnoStuff, false); decodeTechnoStuff() starts by zeroing the values of totalTaskCount (the number of tasks added to the queue so far) and currentTaskNumber (the task currently being run), and then calls updateDisplay() to reset the display to its "noth...
Using the CSS Painting API - Web APIs
for this occasion. li { background-image: paint(hollowHighlights, stroke); } Now we can use the inputArguments() method in the registerPaint() class to access the custom argument we have added to our paint() function. static get inputArguments() { return ['*']; } We then have access to that argument. paint(ctx, size, props, args) { // use our custom arguments const hasStroke = args[0].
toString(); // if stroke arg is 'stroke', don't fill if (hasStroke === 'stroke') { ctx.fillStyle = 'transparent'; ctx.strokeStyle = colour; } ... } We can pass more than one argument. li { background-image: paint(hollowHighlights, stroke, 10px); } We can also specify that we want a particular type of argument. When we get our list of argument values, we ask specifically for a <length> unit.
...the element // args -> list of arguments set when calling the paint() function in the css // where to start the highlight & dimensions const x = 0; const y = size.height * 0.3; const blockWidth = size.width * 0.33; const blockHeight = size.height * 0.85; // the values passed in the paint() function in the CSS const colour = props.get( '--boxColor' ); const strokeType = args[0].
toString(); const strokeWidth = parseInt(args[1]); // set the stroke width if ( strokeWidth ) { ctx.lineWidth = strokeWidth; } else { ctx.lineWidth = 1.0; } // set the fill type if ( strokeType === 'stroke' ) { ctx.fillStyle = 'transparent'; ctx.strokeStyle = colour; } else if ( strokeType === 'filled' ) { ctx.fillStyle = colour; ctx.strokeStyle = colour; } else { ...
Using the CSS Typed Object Model - Web APIs
We've created a blue button wi...
... we included transform: translate3d(1px, 1px, 3px), the .get('transform') would have returned a CSSTranslate with CSSUnitValues for x, y, and z, and the readonly .is2D property would have been false. CSSImageValue Our button has one background image: a magic wand. let bgImage = allComputedStyles.get('background-image'); console.log( bgImage ); // CSSImageValue console.log( bgImage.
toString() ); // url("https://mdn.mozillademos.org/files/16793/magicwand.png") When we get() the 'background-image', a CSSImageValue is returned. While we used the CSS background shorthand property, the inherited Object.prototype.
toString() method, shows we returned only the image, 'url("https://mdn.mozillademos.org/files/16793/magicwand.png")'. Notice that the value returned is the absolute path to th...
Using Fetch - Web APIs
e or request will not cause it to be marked as read in the original. Headers The Headers interface allows you to create your own headers object via the Headers() constructor. ...
... myHeaders = new Headers(); myHeaders.append('Content-Type', 'text/plain'); myHeaders.append('Content-Length', content.length.
toString()); myHeaders.append('X-Custom-Header', 'ProcessThisImmediately'); The same can be achieved by passing an array of arrays or an object literal to the constructor: const myHeaders = new Headers({ 'Content-Type': 'text/plain', 'Content-Length': content.length.
toString(), 'X-Custom-Header': 'ProcessThisImmediately' }); The contents can be queried and retrieved: console.log(myHeaders.has('Content-Type')); // true console.log(myHeaders.has('Set-Cookie')); // false myHeaders.set('Content-Type', 'text/html'); myHeaders.append('X-Custom-Header', 'AnotherValue'); console.log(myHeaders.get('Content-Length')); // 11 console.log(myHeaders.get('X-Custom-Header')); ...
Selection - Web APIs
lectAllChildren() Adds all the children of the specified node to the selection. Selection.setBaseAndExtent() Sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them. Selection.setPosition() Collapses the current selection to a single point. This is an alias for collapse() -- See Selection.collapse() for more details. ...
...DOM nodes, and any content located between them. Selection.setPosition() Collapses the current selection to a single point. This is an alias for collapse() -- See Selection.collapse() for more details. Selection.
toString() Returns a string currently being represented by the selection object, i.e. the currently selected text. Notes String representation of a selection Calling the Selection.
toString() method returns the text contained within the selection, e.g.: var selObj = window.getSelection(); window.alert(selObj); Note that using a selection object as the argument to window.alert will call the object's
toString method. Multiple ranges in a selection A selection object represents the Ranges that the user has selected. Typically, it holds only one range, accessed as follows: var se...
Selection API - Web APIs
cted by the user. Concepts and usage To retrieve the current text range the user has selected, you can use the Window.getSelection() or Document.getSelection() method, storing the return value -- a Selection object -- in a variable for futher use. Once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using Selection.
toString(), adding a range (as represented by a standard Range object) to the selection (or removing one) with Selection.addRange()/Selection.removeRange(), or changing the selection to be the entire contents of a DOM node using Selection.selectAllChildren(). You can run code in response to the selection being changed, or a new selection being started, using the GlobalEventHandlers.onselectionchange and ...
... Opera Full support YesSafari ? WebView Android Full support...
TextEncoder - Web APIs
= (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/); resArr[resPos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/); } } if (typeof Uint8Array !== "undefined") return resArr.subarray(0, resPos + 1); // else // IE 6-9 resArr.length = resPos + 1; // trim off extra weight return resArr; }; TextEncoder.prototype.
toString = function(){return "[object TextEncoder]"}; try { // Object.defineProperty only works on DOM prototypes in IE8 Object.defineProperty(TextEncoder.prototype,"encoding",{ get:function(){if(TextEncoder.prototype.isPrototypeOf(this)) return"utf-8"; else throw TypeError("Illegal invocation");} }); } catch(e) { /*IE6-8 fallback*/ TextEncode...
... Living Standard Initial definition. ...
URL - Web APIs
final ':'. search A USVString indicating the URL's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading ? character. searchParams Read only A URLSearchParams object which can be used to access the individual query parameters found in search. username A USVString containing the username specified before the domain name. Methods
toString() Returns a USVString containing the whole URL. It is a synonym for URL.href, though it can't be used to modify the value. toJSON() Returns a USVString containing the whole URL. It returns the same string as the href property. Static methods createObjectURL() Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely id...
...emonstration.html'; console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html" The URLSearchParams interface can be used to build and manipulate the URL query string. To get the search params from the current window's URL, you can do this: // https://some.site/?id=123 const parsedUrl = new URL(window.location.href); console.log(parsedUrl.searchParams.get("id")); // "123" The
toString() method of URL just returns the value of the href property, so the constructor can be used to normalize and encode a URL directly. const response = await fetch(new URL('http://www.example.com/demonstration.html')); Specifications Specification Status Comment File APIThe definition of 'URL' in that specification. Working Draft Added the static methods URL.crea...
URLSearchParams - Web APIs
given parameter exists. URLSearchParams.keys() Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object. URLSearchParams.set() Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted. URLSearchParams.sort() Sorts all key/value pairs, if any, by their keys. URLSearchParams.
toString() Returns a string containing a query string suitable for use in a URL. URLSearchParams.values() Returns an iterator allowing iteration through all values of the key/value pairs contained in this object. Examples var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. for (let p of searchParams) { cons...
...q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. for (let p of searchParams) { console.log(p); } searchParams.has("topic") === true; // true searchParams.get("topic") === "api"; // true searchParams.getAll("topic"); // ["api"] searchParams.get("foo") === null; // true searchParams.append("topic", "webdev"); searchParams.
toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" searchParams.set("topic", "More webdev"); searchParams.
toString(); // "q=URLUtils.searchParams&topic=More+webdev" searchParams.delete("topic"); searchParams.
toString(); // "q=URLUtils.searchParams" Gotchas The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present. var...
URLUtilsReadOnly - Web APIs
adOnly.pathname Read only Is a DOMString containing an initial '/' followed by the path of the URL. URLUtilsReadOnly.search Read only Is a DOMString containing a '?' followed by the parameters of the URL. URLUtilsReadOnly.hash Read only Is a DOMString containing a '#' followed by the fragment identifier of the URL. Methods This interface doesn't inherit any methods. URLUtilsReadOnly.
toString() Returns a DOMString containing the whole URL. It is a synonym for URLUtilsReadOnly.href. Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome ...
... NoChrome Android No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support No
toString ExperimentalChrome No support NoEdge No support NoFirefox Full support 3.5IE No support NoOpera No support NoSafari No support No...
XMLSerializer - Web APIs
The XMLSerializer interface provides the serialize
ToString() method to construct an XML string representing a DOM tree. Methods serialize
ToString() Returns the serialized subtree of a string. serializeToStream() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. Examples Serializing XML into a string The first, basic, example just serializes an entire document into a string containing XML. var s = new XMLSerializer(); var d = document; var str = s.serialize
ToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serialize
ToString(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the Elemen...
...ith() method (to replace an existing node with the new one) The Document.insertAdjacentElement() and Element.insertAdjacentElement() methods. Because insertAdjacentHTML() accepts a string and not a Node as its second parameter, XMLSerializer is used to first convert the node into a string. var inp = document.createElement('input'); var XMLS = new XMLSerializer(); var inp_xmls = XMLS.serialize
ToString(inp); // First convert DOM node into a string // Insert the newly created node into the document's body document.body.insertAdjacentHTML('afterbegin', inp_xmls); The code creates a new <input> element by calling Document.createElement(), then serializes it into XML using serialize
ToString(). Once that's done, insertAdjacentHTML() is used to insert the <input> element into the DOM. Specificati...
DOM onevent handlers - Developer guides
t the value of the HTML attribute is unaffected by changes to the JavaScript object's property. ...
...erHTML += `${msg}<br>` }; function anchorOnClick(event) { log("Changed onclick handler") }; // Original Handler log(`Element's onclick as a JavaScript property: <code> ${el.onclick.
toString()} </code>`); //Changing handler using .onclick log('<br>Changing onclick handler using <strong> onclick property </strong> '); el.onclick = anchorOnClick; log(`Changed the property to: <code> ${el.onclick.
toString()} </code>`); log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`); //Changing handler using .setAttribute log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> '); el.setAttribute("onclick", 'anchorOnClick(event)'); log(`Changed the property to: <code> ${el.onclick.
toString()} </code>`); log(`Now even the HTML attribute has...
Control flow and error handling - JavaScript
ption and DOMError throw statement Use the throw statement to throw an exception. A throw statement specifies the value to be thrown: throw expression; You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types: throw 'Error2'; // String type throw 42; // Number type throw true; // Boolean type throw {
toString: function() { return "I'm an object!"; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. // Create an object type UserException function UserException(message) { this.message = message; this.name = 'UserException'; } // Make the exception convert to a pretty string when used as a string // (e.g., by the e...
...; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. // Create an object type UserException function UserException(message) { this.message = message; this.name = 'UserException'; } // Make the exception convert to a pretty string when used as a string // (e.g., by the error console) UserException.prototype.
toString = function() { return `${this.name}: "${this.message}"`; } // Create an instance of the object type and throw it throw new UserException('Value too high'); try...catch statement The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it. The try...catch state...
Functions - JavaScript
tion is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example: var y = function x() {}; alert(x); // throws an error The function name also appears when the function is serialized via Function's
toString method. On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared. As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the funct...
...ssion to a variable: var zero; if (shouldDefineZero) { zero = function() { console.log("This is zero."); }; } Examples Returning a formatted number The following function returns a string containing the formatted representation of a number padded with leading zeros. // This function returns a string padded with leading zeros function padZeros(num, totalLen) { var numStr = num.
toString(); // Initialize return value as string var numZeros = totalLen - numStr.length; // Calculate no. of zeros for (var i = 1; i <= numZeros; i++) { numStr = "0" + numStr; } return numStr; } The following statements call the padZeros function. var result; result = padZeros(42,4); // returns "0042" result = padZeros(42,2); // returns "42" result = padZeros(5,4); // re...
BigInt - JavaScript
methods BigInt.asIntN() Wraps a BigInt value to a signed integer between -2width-1 and 2width-1 - 1. BigInt.asUintN() Wraps a BigInt value to an unsigned integer between 0 and 2width - 1. Instance methods BigInt.prototype.toLocaleString() Returns a string with a language-sensitive representation of this number. Overrides the Object.prototype.toLocaleString() method. BigInt.prototype.
toString() Returns a string representing the specified object in the specified radix (base). Overrides the Object.prototype.
toString() method. BigInt.prototype.valueOf() Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method. Usage recommendations Coercion Because coercing between Number and BigInt can lead to loss of precision, it is recommended to onl...
... the two types. Cryptography The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography. Use within JSON Using JSON.stringify() with any BigInt value will raise a TypeError as BigInt values aren't serialized in JSON by default. ...
Intl.Locale.prototype.baseName - JavaScript
of a substring of the complete data string. Specifically, the property returns the substring containing the language, and the script and region if available. baseName returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar. ...
...l.Locale("fr-Latn-CA"); // Sets locale to Canadian French console.log(myLoc.
toString()); // Prints out "fr-Latn-CA-u-ca-gregory" console.log(myLoc.baseName); // Prints out "fr-Latn-CA" Example with options in the input string // Sets language to Japanese, region to Japan, // calendar to Gregorian, hour cycle to 24 hours let japan = new Intl.Locale("ja-JP-u-ca-gregory-hc-24"); console.log(japan.
toString()); // Prints out "ja-JP-u-ca-gregory-hc-h24" console.log(japan.baseName); // Prints out "ja-JP" Example with options that override input string // Input string indicates language as Dutch and region as Belgium, // but options object overrides the region and sets it to the Netherlands let dutch = new Intl.Locale("nl-Latn-BE", {region: "NL"}); console.log(dutch.baseName); // Prints out "nl-Lat...
Intl.Locale.prototype.maximize() - JavaScript
tags. Other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the maximize() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. Examples Using maximize let myLocale = new Intl.Locale("fr", {hourCycle: "h24", calendar: "gregory"}); console.log(myLocale.baseName); // Prints "fr" console.log(myLocale.
toString()); // Prints "fr-u-ca-gregory-hc-h24" let myLocMaximized = myLocale.maximize(); // Prints "fr-Latn-FR". The "Latn" and "FR" tags are added, // since French is only written in the Latin script and is most likely to be spoken in France. console.log(myLocMaximized.baseName); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24". // Note that the extension tags (after "-u") remain unchanged. console.log(myLo...
...nts "fr-u-ca-gregory-hc-h24" let myLocMaximized = myLocale.maximize(); // Prints "fr-Latn-FR". ...
Intl.Locale.prototype.minimize() - JavaScript
ags after the "-u" in the locale indentifier are called extension subtags and are not affected by the minimize() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. ...
...R" console.log(myLocale.
toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24" let myLocMinimized = myLocale.minimize(); // Prints "fr", since French is only written in the Latin script // and is most likely to be spoken in France. console.log(myLocMinimized.baseName); // Prints "fr-u-ca-gregory-hc-h24". // Note that the extension tags (after "-u") remain unchanged. ...
Math.ceil() - JavaScript
ion decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
...rn Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
Math.floor() - JavaScript
djusted value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
...| +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
Object.prototype.hasOwnProperty() - JavaScript
amed prop: o = new Object(); o.hasOwnProperty('prop'); // returns false o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true Direct vs. inherited properties The following example differentiates between direct properties and properties inherited through the prototype chain: o = new Object(); o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true o.hasOwnProperty('
toString'); // returns false o.hasOwnProperty('hasOwnProperty'); // returns false Iterating over the properties of an object The following example shows how to iterate over the properties of an object without executing on inherited properties. Note that the for...in loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown i...
...uld not assume based on the lack of non-enumerable properties shown in the loop that hasOwnProperty itself is confined strictly to enumerable items (as with Object.getOwnPropertyNames()). var buz = { fog: 'stack' }; for (var name in buz) { if (buz.hasOwnProperty(name)) { console.log('this is fog (' + name + ') for sure. ...
Object.prototype.valueOf() - JavaScript
th the preceding code in place, any time an object of type MyNumberType is used in a context where it is to be represented as a primitive value, JavaScript automatically calls the function defined in the preceding code. An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows: myNumberType.valueOf() Note: Objects in string contexts convert via the
toString() method, which is different from String objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function. Examples Using valueOf on custom types function MyNumberType(n) { this.number = n; } MyNumberType.prototype.valueOf = function() { return this.number; }; var myO...
... ...
String - JavaScript
For most languages, this will return the same as toLowerCase(). String.prototype.toLocaleUpperCase( [locale, ...locales]) The characters within a string are converted to uppercase while respecting the current locale. For most languages, this will return the same as toUpperCase(). String.prototype.toLowerCase() Returns the calling string value converted to lowercase. String.prototype.
toString() Returns a string representing the specified object. Overrides the Object.prototype.
toString() method. String.prototype.toUpperCase() Returns the calling string value converted to uppercase. String.prototype.trim() Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard. String.prototype.trimStart() Trims whitespace from the beginning of the string. S...
...For example: let outputStrings = [] for (let i = 0, n = inputValues.length; i < n; ++i) { outputStrings.push(String(inputValues[i])); } Specifications Specification ECMAScript (ECMA-262)The definition of 'String' in that specification. ...
encodeURIComponent() - JavaScript
Component() replacement with an additional replacement of "%20" with "+". ...
... // so we can allow for a little better readability over the wire: |`^ replace(/%(?:7C|60|5E)/g, unescape); } // here is an alternative to the above function function encodeRFC5987ValueChars2(str) { return encodeURIComponent(str). // Note that although RFC3986 reserves "!", RFC5987 does not, // so we do not need to escape it replace(/['()*]/g, c => "%" + c.charCodeAt(0).
toString(16)). // i.e., %27 %28 %29 %2a (Note that valid encoding of "*" is %2A // which necessitates calling toUpperCase() to properly encode) // The following are not required for percent-encoding per RFC5987, // so we can allow for a little better readability over the wire: |`^ replace(/%(7C|60|5E)/g, (str, hex) => String.from...
parseInt() - JavaScript
cal numeral systems). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax parseInt(string [, radix]) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the
ToString abstract operation. Leading whitespace in this argument is ignored. radix Optional An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful--this does not default to 10! The description below explains in more detail what happens when radix is not provided. Return value An integer parsed from the given string. Or NaN when ...
...al). If the first character cannot be converted to a number, parseInt returns NaN. For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation result will also be NaN. To convert a number to its string literal in a particular radix, use thatNumber.
toString(radix). BigInt Warning: parseInt converts a BigInt to a Number and loses precision in the process. This is because trailing non-numeric values, including "n", are discarded. Octal interpretations with no radix Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal...
Equality (==) - JavaScript
to convert them to the same type before comparing: When comparing a number to a string, try to convert the string to a numeric value. If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false. If one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf() and
toString() methods. If the operands have the same type, they are compared as follows: String: return true only if both operands have the same characters in the same order. Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false. Boolean: return true only if operands are both true or both false. ...
... ...
typeof - JavaScript
(logical NOT) operator are equivalent to Boolean() // Symbols typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' // Undefined ...
...Avoid them. typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String('abc') === 'object'; // Functi...
throw - JavaScript
ZipCode constructor does not * conform to one of these patterns, an exception is thrown. ...
... this.value = zip.match(pattern)[0]; this.valueOf = function() { return this.value }; this.
toString = function() { return String(this.value) }; } else { throw new ZipCodeFormatException(zip); } } function ZipCodeFormatException(value) { this.value = value; this.message = 'does not conform to the expected format for a zip code'; this.
toString = function() { return this.value + this.message; }; } /* * This could be in a script that validates address data * for US addresses. */ const ZIPCODE_INVALID = -1; const ZIPCODE_UNKNOWN_ERROR = -2; function verifyZipCode(z) { try { z = new ZipCode(z); } catch (e) { if (e instanceof ZipCodeFormatException) { return ZIPCODE_INVALID; } else { ...
Reddit Example - Archive of obsolete content
Don't intercept the click if it was on one of the links in the header // or next/previous footer, since those links should load in the panel itself. if ($(t).parents('#header').length || $(t).parents('.nextprev').length) return; // Intercept the click, passing it to the addon, which will load it in a tab. event.stopPropagation(); event.preventDefault(); self.port.emit('click', t.
toString()); }); This script uses jQuery to interact with the DOM of the page and the self.port.emit function to pass URLs back to the add-on script. To run this example you'll also have to have an icon file named "icon-16.png" saved in your add-on's "data" directory. You could download this icon: . ...
port - Archive of obsolete content
ire("sdk/self"); var pageMod = pageMods.PageMod({ include: ['*'], contentScriptFile: self.data.url("content-script.js"), onAttach: setupListener }); function setupListener(worker) { worker.port.on('loaded', function(pageInfo) { console.log(pageInfo[0]); console.log(pageInfo[1]); }); } //content-script.js self.port.emit('loaded', [ document.location.
toString(), document.title ]); ...
Content Scripts - Archive of obsolete content
var pageMod = pageMods.PageMod({ include: ['*'], contentScriptFile: self.data.url("content-script.js"), onAttach: startListening }); function startListening(worker) { worker.port.on('click', function(html) { worker.port.emit('warning', 'Do not click this again'); }); } // content-script.js window.addEventListener('click', function(event) { self.port.emit('click', event.target.
toString()); event.stopPropagation(); event.preventDefault(); }, false); self.port.on('warning', function(message) { window.alert(message); }); In the add-on above there are two messages: click is sent from the page-mod to the add-on, when the user clicks an element in the page warning sends a silly string back to the page-mod From Tab.attach() The Tab.attach() method returns the worker yo...
Private Properties - Archive of obsolete content
p: let thumbnails = {}; function getThumbnail(image) { let thumbnail = thumbnails[image]; if (!thumbnail) { thumbnail = createThumbnail(image); thumbnails[image] = thumbnail; } return thumbnail; } There are two problems with the above approach. First, it's not possible to use objects as keys. When an object is used as a key, it's converted to a string using its
toString method. To make the above code work, a unique identifier must be associated with each image and override its
toString method. The second problem is more severe: the thumbnail cache maintains a strong reference to each thumbnail object, so they will never be freed, even when their corresponding image has gone out of scope. This is a memory leak waiting to happen. The above two problems are exactl...
panel - Archive of obsolete content
links inside the panel, and sends the target URL to the main add-on code. The content script sends messages using self.port.emit() and the add-on script receives them using panel.port.on(). var myScript = "window.addEventListener('click', function(event) {" + " var t = event.target;" + " if (t.nodeName == 'A')" + " self.port.emit('click-link', t.
toString());" + "}, false);" var myPanel = require("sdk/panel").Panel({ contentURL: "http://www.bbc.co.uk/mobile/index.html", contentScript: myScript }); myPanel.port.on("click-link", function(url) { console.log(url); }); myPanel.show(); This example uses contentScript to supply the script as a string. It's usually better practice to use contentScriptFile, which is a URL pointing ...
Displaying annotations - Archive of obsolete content
module, asking it to show or hide the annotation. Like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
Bookmarks - Archive of obsolete content
earlier Creating a new bookmark var win = myBrowser.contentWindow; // Get the bookmarks service const BMSVC = Components.classes["@mozilla.org/browser/bookmarks-service;1"] .getService(Components.interfaces.nsIBookmarksService); // Create the bookmark BMSVC.createBookmarkInContainer(win.document.title, // bookmark name win.location.href.
toString(), // URI of the bookmark null, // shortcut win.document.title, // description win.document.characterSet, // charset null, // postData bookmarksService.getBookmarksToolbarFolder(), // bookmark folder 0); // ...
File I/O - Archive of obsolete content
ile object or a string (such as a jar path) See: NetUtil.asyncFetch: Components.utils.import("resource://gre/modules/NetUtil.jsm"); NetUtil.asyncFetch(file, function(inputStream, status) { if (!Components.isSuccessCode(status)) { // Handle error! return; } // The file data is contained within inputStream. // You can read it into a string with var data = NetUtil.readInputStream
ToString(inputStream, inputStream.available()); }); Read with content type hint It's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous I/O). In this case an nsIChannel object has to be explicitly created from the file: Components.utils.import("resource://gre/modules/NetUtil.jsm"); // Content type hint is...
Interaction between privileged and non-privileged pages - Archive of obsolete content
ethingXML.@weight = something.weight; sendMsg("sendSomething", somethingXML); } /** * Send msgs from chrome to the page * @param type {String} the event type. The receiver needs to use that * when doing addEventListener(type, ...) * @param dataXML {E4X} the data or detail */ function sendMsg(type, dataXML) { var el = targetDoc.body; el.setAttribute("eventDataToPage", dataXML ? dataXML.
toString() : ""); var event = targetDoc.createEvent("Event") event.initEvent(type, true, true); el.dispatchEvent(event); } /** * Verifies that the event is indeed coming from our page * as expected, and returns the data for that event. * @returns {E4X} the (unchecked) detail data from the page. * You must check the data. * @see <https://developer.mozilla.org/docs/Code_snippets/ * Interaction_...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
yString.Equals(otherString, CaseInsensitiveCompare)) return NS_OK; // woot, we're equal in all things but case When using unicharutils from frozen-linkage code, link against the unicharutil_external_s static library. The frozen string API doesn't implement the Left(), Mid(), or Right() signatures. Use StringHead(), Substring(), and StringTail() instead: nsString buffer = someString; - nsCAu
toString prefix;- buffer.Left(prefix, 4); + const nsDependentSubstring prefix = StringHead(buffer, 4); The frozen string API doesn't use nsSubstringTuple objects and maintains all strings in a contiguous buffer. This means that the + operator is not implemented, nor are the PromiseFlatString functions or classes around any more. Use += or Append() instead of using +, and use nsString or nsCString instead...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
first .bind() call. Calling .bind() again with removeEventListener will not work. Also, calling .bind() in a tight (inner) loop should be avoided for performance reasons, as calling .bind() does require some work and memory. Overriding/Extending/Amending existing functions A common thing add-ons do during their initialization is overriding/extending existing browser functions by using Function.
toString/Function.toSource and eval to "string-patch" the function body. // DO NOT USE! var functionBody = gBrowser.addTab.toSource(); var afterBracket = functionBody.indexOf("{") + 1; functionBody = functionBody.substring(0, afterBracket) + "myAddon.onAddTab(aURI);" + functionBody.substring(afterBracket); eval("gBrowser.addTab = " + functionBody); Of course, this not only looks messy, but can be quite...
Basics - Archive of obsolete content
tpack.notifications.show("hello world");var myBody = " My first message body on Jetpack";var myIcon = "http://www.mozilla.com/favicon.ico";jetpack.notifications.show({title: "My first message on jetpack", body: myBody, icon: myIcon}); Class Tabs In this class you can find information about the tabs in your Firefox window. The namespace for this class is jetpack.tabs. blah(lengthstringfocusedstring
toStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring
toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady()when the inherited document is fully loaded. onFocus()ch...
File object - Archive of obsolete content
o the file, obeying the same semantics as writeln. File.list() Get a list of files, potentially matching a regular expression filter, from the file. Only has meaning when the file is a directory. File.mkdir() Create a directory. Directory will be created in the same directory as the file, unless the file is a directory, in which case, the directory will be created in that directory. XXX File.
toString() Returns the canonical path to the file. File.toURL() Returns a file:// URL describing the file relative to the local file system. URL is URI-encoded. Examples Example: Hello, world File.output.writeln("Hello, world"); Example: Writing a new file var file = new File("myfile.txt"); file.open("write,create", "text"); file.writeln("The quick brown fox jumped over the lazy dogs"); file.clos...
InstallVersion Object - Archive of obsolete content
should see how to package a plugin as an extension. InstallVersion You use InstallVersion objects to contain version information for software. Overview This object and its methods are used both when triggering a download, to see whether a particular version needs to be installed, and when installing the software. The init() method associates a particular version with an InstallVersion object, the
toString() method converts versions in various formats to a string, and the compareTo() method compares these string and indicates the relationship between the two versions. Each of the version parameters is also available as a separate property of the InstallVersion object. ...
XPInstall API reference - Archive of obsolete content
ch performInstall refreshPlugins registerChrome resetError setPackageFolder InstallTrigger No properties Methods compareVersion enabled getVersion install installChrome startSoftwareUpdate InstallVersion Properties Methods compareTo init
toString File No properties Methods copy dirCreate dirGetParent dirRemove dirRename diskSpaceAvailable execute exists isDirectory isFile macAlias modDate modDateChanged move remove rename size windowsGetShortName windowsRegister...
Namespaces - Archive of obsolete content
property returns the name of the element, without any namespace prefix. The uri property returns the uri of the namespace that the element is in. var info = a.name(); info.localName; // returns 'p'. info.uri; // returns "http://www.w3.org/1999/xhtml" Elements in no namespace return the empty string as their uri. The Namespace global constructor is very similar to QName. Namespace differs in its
toString method, and in that it has a prefix property instead of a localName property. For further information on namespaces in E4X, see Processing XML with E4X. Next is the global XML object. << PreviousNext >> ...
New in JavaScript 1.1 - Archive of obsolete content
vaScript. Changed functionality in JavaScript 1.1 "Object deletion". You can remove an object by setting its object reference to null. constructor and prototype properties on objects added. eval() is now a method of every object (was previously a built-in function); it evaluates a string of JavaScript code in the context of the specified object. Math.random() now works on every platform.
toString(): Added radix parameter, which specifies the base to use for representing numeric values. isNaN() now works on every platform (not only Unix anymore) parseFloat() and parseint() now return NaN on all platforms, if the first character of the specified string cannot be converted to a number; in previous releases, it returned NaN on Solaris and Irix and zero on all other platforms. ...
New in JavaScript 1.2 - Archive of obsolete content
d sorts them to the high end of the array. String.prototype.split() It can take a regular expression argument, as well as a fixed string, by which to split the object string. It can take a limit count so that it won't include trailing empty elements in the resulting array. String.prototype.substring(): no longer swaps index numbers when the first index is greater than the second.
toString(): now converts the object or array to a literal. The break and continue statements can now be used with the new labeled statement. ...
New in JavaScript 1.3 - Archive of obsolete content
gth of the array. Array.prototype.slice(): In JavaScript 1.2, the splice method returned the element removed, if only one element was removed (howMany parameter is 1). In JavaScript 1.3, splice always returns an array containing the removed elements. If one element is removed, an array of one element is returned. Changes to String.prototype.replace(). Changes to the Boolean object. Changes to
toString(). Non-ECMA-262 features of JavaScript 1.3 The following is a comparison between the June 1998 version of ECMA-262 and JavaScript 1.3. The following features were not part of the standard at that time, but implemented in JavaScript 1.3. Keywords and operators Strict equality operators vertical tab (\v or \u000B) as an escape sequence. Statements label switch do...while export imp...
New in JavaScript 1.8.5 - Archive of obsolete content
text provided (with a given sequence of arguments). bug 429507 New ECMAScript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 Function.apply() can accept any array-like object as the arguments list, instead of only true arrays. strict mode support Array.
toString() now works even on non-arrays by either returning the result of calling its join() method if one is available or by calling its
toString() method. Other standardization work Various non-standard syntaxes for defining getters and setters have been removed; ECMAScript 5 defined syntax has not been changed. These were all pretty esoteric and rarely used; if t...
Old Proxy API - Archive of obsolete content
ver, if a fundamental trap is unimplemented, then a call to this trap will throw a TypeError. To make sure no error is thrown when your object is used, you have to implement at least all fundamental traps. Unwanted recursion. Be careful of how you use the receiver argument in 'get' and 'set' traps. var p = Proxy.create({get: function(receiver, name) { print(receiver); // looks for receiver's
toString method. receiver turns out to be the proxy, so calling print results in calling the get trap. return "something"; } }); var q = p.azerty; // infinite loop The receiver argument in 'get' and 'set' traps may not be the proxy itself: var proxy; var handler = { has: function (name) { return name == 'foo'; }, get: function (rcvr, name) { if (name != 'foo') ...
Parsing microformats in JavaScript - Archive of obsolete content
ode. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. Return value An object containing a function you can call to get the string and the HTML. Note: This doesn't return the HTML as a string, but an object with a few functions you can call to retrieve the HTML and do other tasks. The functions you can call on the returned object are: string = html.
toString(); Returns a string using innerText(). string = html.toHTML(); Returns the node's HTML using innerHTML(). string = html.replace(a, b); Returns a string in which all occurrences of a in the HTML are replaced with b. string = html.match(a); Performs the specified matching operation on the HTML and returns the result. iso8601FromDate Converts a JavaScript date object into an ISO 8601 formatted d...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
ost any value, and it will work. Symbols are special. They don't auto-convert. For example: let Sym = Symbol("Sym") alert(Sym) // TypeError: Cannot convert a Symbol value to a string That's a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another. If you really want to show a symbol, we need to call .
toString() on it. let Sym = Symbol("Sym") alert(Sym.
toString()) // Symbol(Sym), now it works Or you can use the symbol.description property to get its description: let _Sym = Symbol("Sym"); alert(_Sym.description); // Sym Well-known symbols The Symbol class has constants for so-called well-known symbols. These symbols let you configure how JS treats an object, by using them as property keys. Examp...
Handling text — strings in JavaScript - Learn web development
nt to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs: The Number object converts anything passed to it into a number, if it can. Try the following: let myString = '123'; let myNum = Number(myString); typeof myNum; Conversely, every number has a method called
toString() that converts it to the equivalent string. Try this: let myNum = 123; let myString = myNum.
toString(); typeof myString; These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through Number() to ...
How to implement a custom autocomplete search component
ts.results.NS_ERROR_NO_INTERFACE; }, canUnload: function(aCompMgr) { return true; } }; // Module initialization function NSGetModule(aCompMgr, aFileSpec) { return SimpleAutoCompleteSearchModule; } Starting in Gecko 2.0, component registration has been changed, so you need to make the following changes: Add an NSGetFactory() function: function NSGetFactory(cid) { if (cid.
toString().toUpperCase() != CLASS_ID.
toString().toUpperCase()) { throw Components.results.NS_ERROR_FACTORY_NOT_REGISTERED; } return SimpleAutoCompleteSearchFactory; } You need to explicitly register the component by adding these lines into your chrome.manifest file: component {6224daa1-71x2-4d1a-ad90-01ca1c08e323} components/.js contract @mozilla.org/autocomplete/search...
Network Addresses
in a polymorphic manner. By using these functions with other network address functions, clients can support either version 4 or version 6 of the Internet Protocol transparently. All NSPR functions that require PRNetAddr as an argument accept either an IPv4 or IPv6 version of the address. ...
S/MIME functions
ficate MXR 3.2 and later NSS_CMSSignerInfo_GetSigningTime MXR 3.2 and later NSS_CMSSignerInfo_GetVerificationStatus MXR 3.2 and later NSS_CMSSignerInfo_GetVersion MXR 3.2 and later NSS_CMSSignerInfo_IncludeCerts MXR 3.2 and later NSS_CMSUtil_VerificationStatus
ToString MXR 3.2 and later NSS_SMIMESignerInfo_SaveSMIMEProfile MXR 3.4 and later NSS_SMIMEUtil_FindBulkAlgForRecipients MXR 3.2 and later ...
Rhino overview
CMA conformant. Operators == and != Version 1.2 only uses strict equality for the == and != operators. In version 1.3 and greater, == and != have the same meanings as ECMA. The operators === and !== use strict equality in all versions. ToBoolean Boolean(new Boolean(false)) is false for all versions before 1.3. It is true (and thus ECMA conformant) for version 1.3 and greater. Array.prototype.
toString and Object.prototype.
toString Version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example). In version 1.3 and greater these functions are ECMA conformant. Array constructor Array(i) for a number argument i constructs an array with a single element equal to i for version 1.2 only. Otherwise the ECMA conformant version is used (an array is constructed with no el...
Performance Hints
hold the contents of the JavaScript array. eval and new Function Avoid calling eval when possible. Calls to eval are slow because the script being executed must be compiled. Constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. For example, the code function MyObject(a) { this.s = a; this.
toString = new Function("return this.s"); } could be written more efficiently as function MyObject(a) { this.s = a; this.
toString = function () { return this.s } } Beginning with Rhino 1.4 Release 2, code passed to eval and new Function will be interpreted rather than compiled to class files. with Using the with statement prevents the compiler from generating code for fast access to local v...
Scripting Java
thods is particularly useful in exploratory programming where we might be investigating a method and are unsure of the parameter or return types. Another useful feature for exploratory programming is the ability to see all the methods and fields defined for an object. Using the JavaScript for..in construct, we can print out all these values: js> for (i in f) { print(i) } exists parentFile mkdir
toString wait [44 others] Note that not only the methods of the File class are listed, but also the methods inherited from the base class java.lang.Object (like wait). This makes it easier to work with objects in deeply nested inheritance hierarchies since you can see all the methods that are available for that object. Rhino provides another convenience by allowing properties of JavaBeans to be accesse...
Exact Stack Rooting
s highly recommended that this rooting mechanism only be used on the CStack. js::Rooted<T> typedef js::Rooted<T> RootedT; -> RootedObject, RootedString, RootedScript, etc. Because of the LIFO restriction, using this interface manually is extremely cumbersome. Instead, SpiderMonkey has a convenient suite of C++ RAII classes to do this for you, called js::RootedT: RootedString str1(cx, JS_Value
ToString(cx, val)); RootedString str2(rt, JS_Value
ToString(cx, val)); Note 1: C++ insists that an initializing assignment (e.g., the default constructor followed by operator=) must have a copy constructor available, even if it is not used. Since it is never correct to implicitly copy a js::RootedT (more on this in a second) we have deleted the copy constructor from these classes. Therefore, we are forc...
Property cache
or a pointer to the js::Shape if not. The opcodes that take advantage of the property cache, as of June 2009, are: GETPROP, GET{X,THIS,ARG,LOCAL}PROP, and LENGTH; NAME; SETPROP, BINDNAME, and SETNAME; CALLPROP and CALLNAME; and {INC,DEC}NAME and NAME{INC,DEC}. ELEM opcodes do not use it. Nor do {INC,DEC}PROP or PROP{INC,DEC}. Nor do operations such as ADD that only need to look up a property (.
toString) in unusual cases. Throughout this article, phrases such as "own property" should be taken to refer to the low-level representation of properties in scopes and Shape chains. In the case of SHARED PERMANENT properties, this differs from the notion of "own property" seen by scripts via Object.prototype.hasOwnProperty. Shape Native objects have a shape, a 24-bit unsigned integer such that: ...
JSAPI User Guide
ge collection below for crucial information on how to use JS::Values safely. JS::Value includes member functions to test the JavaScript data type. These are isObject(), isNumber(), isInt32(), isDouble(), isString(), isBoolean(), isNull(), and isUndefined(). If a JS::Value contains a JSObject, double, or JSString, you can cast it to its underlying data type using the toObject(), toDouble(), and
toString() member functions, respectively. This is useful in some cases where your application or a JSAPI function requires a variable or argument of a specific data type, rather than a JS::Value. Similarly, you can create a JS::Value wrapping a JSObject, double, or JSString pointer to a JS::Value using JS::ObjectValue(JSObject&), JS::DoubleValue(double), or JS::StringValue(JSString*). Garbage collection...
JSExtendedClass.wrappedObject
l JSExtendedClass.wrappedObject, then objects of that class may be wrappers. In a few cases the JavaScript engine will pretend the wrapper isn't there, instead operating on the object it wraps. In these cases the engine calls the JSExtendedClass.wrappedObject callback to get the wrapped object. Most classes do not implement wrappedObject. The specific cases where this happens are: The default
toString method returns a string that contains the name of the wrapped object's class rather than the wrapper's class. In typeof expressions and in JS_TypeOfValue, the type of the wrapped object is returned. (The result may be "object", "function", or "xml".) When assigning to __proto__ or __parent__ from script, the JavaScript engine checks to see if the assignment would produce a cycle. If so, i...
JSVAL_TO_STRING
e removed at any time. Try to avoid using it. Cast a jsval to type JSString * without a type check. Syntax JSString * JSVAL_TO_STRING(jsval v); Description JSVAL_TO_STRING casts the argument, v, to type JSString *. As a precondition, JSVAL_IS_STRING(v) must be true. This function is not type-safe: if v is not a string, the behavior is undefined. To coerce any value to a string, use the JS_Value
ToString function instead. (The difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) To convert the return type of this macro (JSString *) to a char pointer, use JS_GetStringBytes. See Also bug 952650 ...
JS_ValueToNumber
JSObjectOps.defaultValue hook, so host objects can override it all.) First, the object's JSClass.convert callback is called. For objects of standard classes, this is JS_ConvertStub, which simply calls v.valueOf() if present. If the convert callback produces a primitive value, the value is converted to a number as described above and conversion succeeds. Otherwise, the resulting object's
toString method, if any, is called. If that produces a primitive value, the value is converted to a number as described above and conversion succeeds. Otherwise conversion fails with a TypeError. On success, JS_ValueToNumber stores the converted value in *dp and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *dp is undefined. See Also JS_ConvertArguments ...
SavedFrame
ise was created. If the frame responsible for the call is not accessible to the caller, this points to the youngest accessible ancestor of the real frame, if any. In all other cases, this is null. parent This stack frameaEUR(TM)s caller, or null if this is the oldest frame on the stack. In this case, there might be an asyncParent instead. Function Properties of the SavedFrame.prototype Object
toString Return this frame and its parents formatted as a human readable stack trace string. Source Metadata Generated from file: js/src/doc/SavedFrame/SavedFrame.md Watermark: sha256:3475238d6704c659cb3e411b9c601d6ee836762dea14203f1f00ecf2c3b32452 Changeset: 251fccc1f62b ...
Shell global objects
n as directed by 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 } Call the object params.function with no arguments. { object, property } Fetch the property named params.property of params.object. {
ToString } Apply JS::
ToString to params.
toString. { ToNumber } Apply JS::ToNumber to params.toNumber. { eval } Apply JS::Evaluate to params.eval. The return value is an array of strings, with one element for each JavaScript invocation that occurred as a result of the given operation. Each element is the name of the function invoked, or the string 'eval:FILENAME' if the code was invoked by eva...
An Overview of XPCOM
port the interface an error is returned. class nsISupports { public: long QueryInterface(const nsIID & uuid, void **result) = 0; long AddRef(void) = 0; long Release(void) = 0; }; The first parameter of QueryInterface is a reference to a class named nsIID, which is a basic encapsulation of the IID. Of the three methods on the nsIID class, Equals, Parse, and
ToString, Equals is by far the most important, because it is used to compare two nsIIDs in this interface querying process. When you implement the nsISupports class (and you'll see in the chapter Using XPCOM Utilities to Make Things Easier how macros can make this process much easier), you must make sure the class methods return a valid result when the client calls QueryInterface with the nsISupports IID...
XPCOM Stream Guide
JavaScript modules are your friends There are several useful JavaScript modules at your disposal. For streams, the most obvious are NetUtil.jsm and FileUtils.jsm. NetUtil.jsm provides APIs for copying an input stream to an output stream (the asyncCopy() method), getting an input stream from another source (the asyncFetch() method), and reading an input stream into a string (the readInputStream
ToString() method). FileUtils.jsm provides APIs for getting output streams for files, with the .openFileOutputStream(file, modeFlags) and .openSafeFileOutputStream(file, modeFlags) methods, and for closing those output streams with the .closeSafeFileOutputStream(inputStream) method. As we mentioned earlier, you can use the IO service to get any channel, and from there an input stream. The IO service is ...
XPConnect wrappers
n any natively implemented XPCOM object (that is, any object implemented in C++) needs to be reflected into JavaScript. This includes all DOM objects (including Window) and chrome elements that are reflected into JavaScript. This wrapper is responsible for mapping calls from JavaScript into C++. This means that when you say window.focus(), you're calling into XPCWrappedNative code. If you call '
toString()' and get "[xpconnect wrapped nsIFoo]" then the reference is to a XPCWrappedNative object with interface nsIFoo. They are implicitly created by XPConnect and you should not have to worry about how that happens. There are several types of wrapped natives, but I won't cover those here. XPCWrappedJS These objects are the exact opposite of XPCWrappedNative. They exist to reflect an object from Ja...
nsACString (External)
a alt="" coords="731,198,955,246" href="http://developer.mozilla.org/en/nsDependentCSubstring_external" shape="rect" title="nsDependentCSubstring_external"> <area alt="" coords="979,198,1123,246" href="http://developer.mozilla.org/en/PromiseFlatCString_(External)" shape="rect" title="PromiseFlatCString_(External)"> <area alt="" coords="1147,198,1259,246" href="http://developer.mozilla.org/en/nsCAu
toString_(External)" shape="rect" title="nsCAu
toString_(External)"> <area alt="" coords="5,294,208,342" href="http://developer.mozilla.org/en/nsDependentCString_external" shape="rect" title="nsDependentCString_external"> <area alt="" coords="232,294,475,342" href="http://developer.mozilla.org/en/NS_ConvertUTF16toUTF8_external" shape="rect" title="NS_ConvertUTF16toUTF8_external"> <area alt="" coords="499,2...
nsACString_internal
ng" shape="rect" title="nsXPIDLCString"> <area alt="" coords="461,197,611,245" href="http://developer.mozilla.org/en/nsDependentCString" shape="rect" title="nsDependentCString"> <area alt="" coords="635,197,787,245" href="http://developer.mozilla.org/en/nsPromiseFlatCString" shape="rect" title="nsPromiseFlatCString"> <area alt="" coords="173,293,285,341" href="http://developer.mozilla.org/en/nsCAu
toString" shape="rect" title="nsCAu
toString"> <area alt="" coords="5,389,227,437" href="http://developer.mozilla.org/en/NS_LossyConvertUTF16toASCII" shape="rect" title="NS_LossyConvertUTF16toASCII"> <area alt="" coords="251,389,435,437" href="http://developer.mozilla.org/en/NS_ConvertUTF16toUTF8" shape="rect" title="NS_ConvertUTF16toUTF8"> <area alt="" coords="309,293,445,341" href="http://developer.mozil...
nsAString (External)
<area alt="" coords="700,198,913,246" href="http://developer.mozilla.org/en/nsDependentSubstring_external" shape="rect" title="nsDependentSubstring_external"> <area alt="" coords="937,198,1071,246" href="http://developer.mozilla.org/en/PromiseFlatString_(External)" shape="rect" title="PromiseFlatString_(External)"> <area alt="" coords="1095,198,1196,246" href="http://developer.mozilla.org/en/nsAu
toString_(External)" shape="rect" title="nsAu
toString_(External)"> <area alt="" coords="5,294,197,342" href="http://developer.mozilla.org/en/nsDependentString_external" shape="rect" title="nsDependentString_external"> <area alt="" coords="221,294,467,342" href="http://developer.mozilla.org/en/NS_ConvertASCIItoUTF16_external" shape="rect" title="NS_ConvertASCIItoUTF16_external"> <area alt="" coords="491,29...
nsAString_internal
DLString" shape="rect" title="nsXPIDLString"> <area alt="" coords="420,197,559,245" href="http://developer.mozilla.org/en/nsDependentString" shape="rect" title="nsDependentString"> <area alt="" coords="583,197,727,245" href="http://developer.mozilla.org/en/nsPromiseFlatString" shape="rect" title="nsPromiseFlatString"> <area alt="" coords="152,293,253,341" href="http://developer.mozilla.org/en/nsAu
toString" shape="rect" title="nsAu
toString"> <area alt="" coords="5,389,192,437" href="http://developer.mozilla.org/en/NS_ConvertASCIItoUTF16" shape="rect" title="NS_ConvertASCIItoUTF16"> <area alt="" coords="216,389,400,437" href="http://developer.mozilla.org/en/NS_ConvertUTF8toUTF16" shape="rect" title="NS_ConvertUTF8toUTF16"> <area alt="" coords="277,293,405,341" href="http://developer.mozilla.org/en/n...
XPCOM glue classes
r arrays.nsAString (External)Class DeclarationnsAString_internalClass DeclarationnsAutoRefnsAutoRef<t> is a template class implementing an object that holds a handle to a resource that must be released, typically on destruction of the object.</t>nsAutoRefTraitsnsAutoRefTraits<t> is a template class describing traits of resources held by objects of class nsAutoRef<T> and/or nsCountedRef<T>.</t>nsAu
toStringClass DeclarationnsAu
toString (External)Class DeclarationnsCAu
toStringClass DeclarationnsCAu
toString (External)Class DeclarationnsCOMPtrThis utility class simplifies managing XPCOM interface references from C++ code.nsCountedRefnsCountedRef<t> is a template class implementing an object that takes a strong reference to a reference-counted resource that must be released, typically on destruction of ...
nsIDOMNSHTMLDocument
tirely in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). boolean execCommandShowHelp( in DOMString commandID ); Parameters commandID The name of the command. Return value This method is not supported and always throws an exception. getSelection() DOMString getSelection(); Parameters None. Return value The text of the current selection, the same as window.getSelection.
toString(). open() nsIDOMDocument open( in ACString aContentType, in boolean aReplace ); Parameters aContentType The content type of the new document. If the type is not supported by the HTML content sink, trying to write to the document will probably throw. aReplace Whether the document should replace the existing document in session history. Return value The new document. queryCom...
nsIMsgAccount
nsIMsgAccount mailnews/base/public/nsIMsgAccount.idlScriptable An account consists of an incoming server and one or more outgoing identities. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void addIdentity(in nsIMsgIdentity identity); void clearAllValues(); void init(); void removeIdentity(in nsIMsgIdentity identity); AString
toString(); Attributes Attribute Type Description defaultIdentity nsIMsgIdentity identities nsISupportsArray Read only. Outgoing identity list (array of nsIMsgIdentity's) incomingServer nsIMsgIncomingServer Incoming server stuff key ACString Internal key identifying itself Methods addIdentity() Adds a new identity to this account. void addIdentity( in nsIMsgIdentity identity ); Parameters identity The ide...
nsIMsgSearchValue
ng age; // in days attribute nsIMsgFolder folder; attribute nsMsgLabelValue label; attribute nsMsgJunkStatus junkStatus; /* * junkPercent is set by the message filter plugin, and is approximately * proportional to the probability that a message is junk. * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString
toString(); }; ...
nsIScriptableInputStream
stream would block the calling thread (non-blocking mode only). Remarks This interface provides JavaScript with a way to read ASCII text from a nsIInputStream. However, it does not address the problem of reading arbitrary binary data from a stream. For binary input see nsIBinaryInputStream. Note: Starting in Gecko 2.0, you can use the NetUtils.jsm JavaScript code module and its readInputStream
ToString() method to read arbitrary binary data into a JavaScript string. The nsScriptableInputStream component implements this interface. This interface was frozen for Gecko 1.2. From Gecko 2.0 interfaces are no longer frozen. Examples List contents of XPI and read file contents This example here uses the read function. It takes a input stream from the zip reader and outputs the text in it. Full example...
nsISupportsCString
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for ASCII character strings. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data ACString Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsChar
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for single character values (often used to store an ASCII character). Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data char Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsDouble
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for double-precision floating-point values. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data double Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsFloat
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for single-precision floating-point values. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data float Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsID
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for boolean values. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data nsIDPtr Provides access to the native type represented by the object. Methods
toString() This method returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsInterfacePointer
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for XPCOM objects. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data nsISupports Provides access to the native type represented by the object. dataIID nsIDPtr Stores an IID corresponding to the data attribute. Methods
toString() Returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRBool
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for boolean values. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRBool Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt16
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 16-bit signed integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRInt16 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt32
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 32-bit signed integers. 66 Introduced Gecko 1.0 Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRInt32 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt64
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 64-bit signed integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRInt64 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRTime
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for PRTime values. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRTime Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint16
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 16-bit unsigned integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRUint16 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint32
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 32-bit unsigned integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRUint32 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint64
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 64-bit unsigned integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRUint64 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint8
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for 8-bit unsigned integers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data PRUint8 Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsString
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for Unicode character strings. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.2 Method overview string
toString(); Attributes Attribute Type Description data AString Provides access to the native type represented by the object. Methods
toString() This methods returns a string valued representation of the object. string
toString(); Parameters None. Return value A string valued representation of the object. Remarks This interface was frozen for Gecko 1.2. See bug 166426 for details. From Gecko 2.0 interfaces are no longer frozen. ...
nsISupportsVoid
xpcom/ds/nsISupportsPrimitives.idlScriptable This interface provides scriptable access for generic pointers. Inherits from: nsISupportsPrimitive Last changed in Gecko 1.0 Method overview string
toString(); Attributes Attribute Type Description data voidPtr This attribute provides access to the native type represented by the object. Native code only! Methods
toString() string
toString(); Parameters None. Return value A string valued representation of the object. ...
nsIMsgSearchValue
ng age; // in days attribute nsIMsgFolder folder; attribute nsMsgLabelValue label; attribute nsMsgJunkStatus junkStatus; /* * junkPercent is set by the message filter plugin, and is approximately * proportional to the probability that a message is junk. * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString
toString(); }; ...
Mail and RDF
In the example of mail folders, each folder datasource first registers itself with the mail session as a nsIFolderListener because it wants information about when a folder...
Using COM from js-ctypes
e', WINABI, HRESULT, // return REFCLSID, // rclsid LPUNKNOWN, // pUnkOuter DWORD, // dwClsContext REFIID, // riid LPVOID // *ppv ); // HELPER FUNCTIONS function checkHRESULT(hr /*primative HRESULT*/, funcName /*jsStr*/) { // primative because thats what is returned by declared functions that // return HRESULT hr = hr.
toString(); // makes it primative if (hr < 0) { console.error('HRESULT', hr, 'returned from function ', funcName /*, 'getStrOfResult:', getStrOfResult(hr)*/); throw new Error('HRESULT ' + hr + ' returned from function ' + funcName); } } let CLSIDFromArr = IIDFromArr = function(jsArr_pieces) { let guid = GUID(); // CLSID and IID are same they are GUID ...
ABI
ll on Windows, but do not have mangled names like those used by stdcall_abi above. OS Specific WIN32 and OS2 Callbacks in js-ctypes under these operating systems use a different ABI than regular function declarations. Other All other operating systems use ctypes.default_abi as their calling convention for all function declarations. Method overview String toSource() String
toString() Methods toSource() Returns the string "ctypes.***_abi". String toSource() Parameters None. Return value A JavaScript expression that evaluates to the ABI.
toString() Returns a string identifying the ABI. String
toString(); Parameters None. Return value A string identifying the ABI. See Also ctypes FunctionType Library ...
FunctionType
ting the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String
toString() FunctionType CData FunctionType CData cannot be constructed. Function pointer is created with FunctionType.ptr. CData functiontype.ptr([func]); functiontype is FunctionType CType. Parameters func A pointer value or JavaScript Function. Return value A CData representing the newly allocated function pointer. Exceptions thrown TypeError func is not either pointer value or J...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
r log = dbg.memory.drainAllocationsLog(); // Neutralize the Debugger, and drop it on the floor // for the GC to collect. console.log("Stopping allocation tracking."); dbg.removeAllDebuggees(); dbg = undefined; // Analyze and display the allocation log. plot(log); } function handleUncaughtException(ex) { console.log('Debugger hook threw:'); console.log(ex.
toString()); console.log('Stack:'); console.log(ex.stack); }; function plot(log) { // Given the log, compute a map from allocation sites to // allocation counts. Note that stack entries are '===' if // they represent the same site with the same callers. var counts = new Map; for (let site of log) { // This is a kludge, necessary for now. The saved stacks // are...
Web Console remoting - Firefox Developer Tools
", "result": { "type": "object", "className": "HTMLDocument", "actor": "conn0.consoleObj20" "extensible": true, "frozen": false, "sealed": false }, "timestamp": 1347306273605, "exception": null, "exceptionMessage": null, "helperResult": null } exception holds the JSON-ification of the exception thrown during evaluation. exceptionMessage holds the exception.
toString() result. result has the result ObjectActor instance. helperResult is anything that might come from a JSTerm helper result, JSON stuff (not content objects!). In Firefox 23: we renamed the error and errorMessage properties to exception and exceptionMessage respectively, to avoid conflict with the default properties used when protocol errors occur. Autocomplete and more The autocomplete re...
CSSNumericValue.add() - Web APIs
yntax var cssMathSum = CSSNumericValue.add(double | CSSNumericValue); Parameters number either a Number or a CSSNumericValue. Return value A CSSMathSum Exceptions TypeError Indicates that an invalid type was passed to the method. Examples let mathSum = CSS.px("23").add(CSS.percent("4")).add(CSS.cm("3")).add(CSS.in("9")); // Prints "calc(23px + 4% + 3cm + 9in)" console.log(mathSum.
toString()); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'add' in that specification. Working Draft Initial definition. ...
CSSNumericValue.div() - Web APIs
face divides the CSSNumericValue by the supplied value. Syntax var cssNumericValue = CSSNumericValue.div(number); Parameters number Either a Number or a CSSNumericValue. Return value A CSSMathProduct. Exceptions TypeError Indicates that an invalid type was passed to the method. Examples let mathProduct = CSS.px("24").div(CSS.percent("4")); // Prints "calc(24px / 4%)" mathProduct.
toString(); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'div' in that specification. Working Draft Initial definition. ...
CSSNumericValue.max() - Web APIs
bern); Parameters number Either a Number or a CSSNumericValue. Return value A CSSUnitValue. Exceptions TypeError Indicates that an invalid type was passed to the method. Examples As stated earlier, all passed values must be of the same type and value. Some of the following examples illustrate what happens when they are not. // Prints "2cm" console.log(CSS.cm("1").max(CSS.cm("2")).
toString()); // Prints "max(1cm, 0.393701in)" console.log(CSS.cm("1").max(CSS.in("0.393701")).
toString()); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'max' in that specification. Working Draft Initial definition. ...
CSSNumericValue.min() - Web APIs
bern); Parameters number Either a Number or a CSSNumericValue. Return value A CSSUnitValue. Exceptions TypeError Indicates that an invalid type was passed to the method. Examples As stated earlier, all passed values must be of the same type and value. Some of the following examples illustrate what happens when they are not. // Prints "1cm" console.log(CSS.cm("1").min(CSS.cm("2")).
toString()); // Prints "max(1cm, 0.393701in)" console.log(CSS.cm("1").max(CSS.in("0.393701")).
toString()); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'min' in that specification. Working Draft Initial definition. ...
CSSNumericValue.mul() - Web APIs
value. Syntax var cssMathProduct = CSSNumericValue.mul(number); Parameters number Either a Number or a CSSNumericValue. Return value A CSSMathProduct Exceptions TypeError Indicates that an invalid type was passed to the method. Examples let mathSum = CSS.px("23").mul(CSS.percent("4")).mul(CSS.cm("3")).mul(CSS.in("9")); // Prints "calc(23px * 4% * 3cm * 9in)" console.log(mathSum.
toString()); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'mul' in that specification. Working Draft Initial definition. ...
CSSNumericValue.sub() - Web APIs
the CSSNumericValue. Syntax var cssMathSum = CSSNumericValue.sub(number); Parameters number Either a Number or a CSSMathSum. Return value A CSSMathSum Exceptions TypeError Indicates that an invalid type was passed to the method. Examples let mathSum = CSS.px("23").sum(CSS.percent("4")).sum(CSS.cm("3")).sum(CSS.in("9")); // Prints "calc(23px - 4% - 3cm - 9in)" console.log(mathSum.
toString()); And/or include a list of links to useful code samples that live elsewhere: Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'sub' in that specification. Working Draft Initial definition. ...
CSSNumericValue.sum() - Web APIs
the CSSNumericValue. Syntax var cssMathSum = CSSNumericValue.sub(number); Parameters number Either a Number or a CSSMathSum Return value A CSSMathSum Exceptions TypeError Indicates that an invalid type was passed to the method. Examples let mathSum = CSS.px("23").sum(CSS.percent("4")).sum(CSS.cm("3")).sum(CSS.in("9")); // Prints "calc(23px - 4% - 3cm - 9in)" console.log(mathSum.
toString()); And/or include a list of links to useful code samples that live elsewhere: Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'sub' in that specification. Working Draft Initial definition. ...
CSSNumericValue.to() - Web APIs
beric value from one unit to another. Syntax var cssUnitValue = CSSNumericValue.to(unit); Parameters unit The unit to which you want to convert. Return value A CSSMathSum. Exceptions SyntaxError Indicates that an invalid type was passed to the method. TypeError Indicates that the passed values cannot be summed. Examples // Prints "0.608542cm" console.log(CSS.px("23").to("com").
toString()); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'to' in that specification. Working Draft Initial definition. ...
CSSNumericValue.toSum() - Web APIs
value to a CSSMathSum object to values of the specified unit. Syntax var cssMathSum = CSSNumericValue.toSum(units); Parameters units The units to convert to. Return value A CSSNumericValue. Exceptions SyntaxError undefined TypeError Indicates that an invalid type was passed to the method. Examples let v = CSS.px("23").add(CSS.percent("4")).add(CSS.cm("3")).add(CSS.in("9")); v.
toString() // => "calc(23px + 4% + 3cm + 9in)" v.toSum("px", "percent").
toString() // => "calc(1000.39px + 4%)" Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'toSum' in that specification. Working Draft Initial definition. ...
CSS Painting API - Web APIs
nputProperties() { return ['--boxColor']; } static get inputArguments() { return ['*','<length>']; } static get contextOptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockWidth = size.width * 0.33; const blockHeight = size.height * 0.85; const theColor = props.get( '--boxColor' ); const strokeType = args[0].
toString(); const strokeWidth = parseInt(args[1]); console.log(theColor); if ( strokeWidth ) { ctx.lineWidth = strokeWidth; } else { ctx.lineWidth = 1.0; } if ( strokeType === 'stroke' ) { ctx.fillStyle = 'transparent'; ctx.strokeStyle = theColor; } else if ( strokeType === 'filled' ) { ctx.fillStyle = theColor; ctx.strokeStyle = theColor; } else { ctx.fillStyle =...
DOMMatrixReadOnly.flipX() - Web APIs
g> This JavaScript first creates an identity matrix, then uses the `flipX()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place. const flipped = document.getElementById('flipped'); const matrix = new DOMMatrixReadOnly(); const flippedMatrix = matrix.flipX(); flipped.setAttribute('transform', flippedMatrix.
toString()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.flipX()' in that specification. Candidate Recommendation Initial definition ...
DOMMatrixReadOnly.translate() - Web APIs
" width="25" height="25" fill="blue" /> </svg> The following JavaScript first creates an identity matrix, then uses the translate() method to create a new, translated matrix -- which is then applied to the blue square as a transform. The red square is left in place. const matrix = new DOMMatrixReadOnly().translate(25, 25); document.querySelector('#transformed').setAttribute('transform', matrix.
toString()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.translate()' in that specification. Candidate Recommendation Initial definition ...
DOMMatrixReadOnly - Web APIs
m42, m43, m44) which comprise the matrix. The elements are stored into the array as double-precision floating-point numbers in column-major (colexographical access access or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.) DOMMatrixReadOnly.toJSON() Returns a JSON representation of the DOMMatrixReadOnly object. DOMMatrixReadOnly.
toString() Creates and returns a DOMString object which contains a string representation of the matrix in CSS matrix syntax, using the appropriate CSS matrix notation. See the matrix() CSS function for details on this syntax. For a 2D matrix, the elements a through f are listed, for a total of six values and the form matrix(a, b, c, d, e, f). For a 3D matrix, the returned string contains all 16 el...
DirectoryReaderSync - Web APIs
ntries(dirReader) { var entries = dirReader.readEntries(); for (var i = 0, entry; entry = entries[i]; ++i) { // Stash this entry's filesystem in URL paths.push(entry.toURL()); // If this is a directory, traverse. if (entry.isDirectory) { getAllEntries(entry.createReader()); } } } // Forward the error to main app. function onError(e) { postMessage('ERROR: ' + e.
toString()); } self.onmessage = function(e) { var data = e.data; // Ignore everything else except our 'list' command. if (!data.cmd || data.cmd != 'list') { return; } try { var fs = requestFileSystemSync(TEMPORARY, 1024*1024 /*1MB*/); getAllEntries(fs.root.createReader()); self.postMessage({entries: paths}); } catch (e) { onError(e); } }; Method overview ...
Document.createCDATASection() - Web APIs
ent.createCDATASection(data); CDATASectionNode is a CDATA Section node. data is a string containing the data to be added to the CDATA Section. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml') var cdata = docu.createCDATASection('Some <CDATA> data & then some'); docu.getElementsByTagName('xml')[0].appendChild(cdata); alert(new XMLSerializer().serialize
ToString(docu)); // Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml> Notes This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]]>") as part of the data, so unescaped...
Document.createComment() - Web APIs
ntax CommentNode = document.createComment(data); Parameters data A string containing the data to be added to the Comment. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml'); var comment = docu.createComment('This is a not-so-secret comment in your document'); docu.getElementsByTagName('xml')[0].appendChild(comment); alert(new XMLSerializer().serialize
ToString(docu)); // Displays: <xml><!--This is a not-so-secret comment in your document--></xml> Specifications Specification Status Comment DOMThe definition of 'document.createComment' in that specification. Living Standard ...
Document.createProcessingInstruction() - Web APIs
two, other than standardized ones such as <?xml-stylesheet ?>. The closing processing instruction sequence (?>) is part of the data. Example var doc = new DOMParser().parseFromString('<foo />', 'application/xml'); var pi = doc.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertBefore(pi, doc.firstChild); console.log(new XMLSerializer().serialize
ToString(doc)); // Displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> Specifications Specification Status Comment DOMThe definition of 'createProcessingInstruction()' in that specification. Living Standard No change DOM4The definition of 'createProcessingInstruction()' in that specification. Obsolete Added more explicit definition of how...
Document.mozSetImageElement() - Web APIs
height: 400px; cursor: pointer; } </style> The CSS defined by the <style> block above is used by our <div> to use an element with the id "canvasbg" as its background. var c = 0x00; function clicked() { var canvas = document.createElement("canvas"); canvas.setAttribute("width", 100); canvas.setAttribute("height", 100); var ctx = canvas.getContext('2d'); ctx.fillStyle = "#" + c.
toString(16) + "0000"; ctx.fillRect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozSetImageElement("canvasbg", canvas); } The code here is called each time the user clicks the <div> element. It creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square. Each time the function is called, the square is a different col...
Element.classList - Web APIs
") (function(window){ var document = window.document, Object = window.Object, hasOwnProp = Object.prototype.hasOwnProperty; var defineProperty = Object.defineProperty, allowTokenListConstruction = 0, skipPropChange = 0; function DOMTokenList(){ if (!allowTokenListConstruction) throw TypeError("Illegal constructor"); // internally let it through } DOMTokenList.prototype.
toString = DOMTokenList.prototype.toLocaleString = function(){return this.value}; DOMTokenList.prototype.add = function(){ a: for(var v=0, argLen=arguments.length,val="",ele=this[" uCL"],proto=ele[" uCLp"]; v!==argLen; ++v) { val = arguments[v] + "", checkIfValidClassListEntry("add", val); for (var i=0, Len=proto.length, resStr=val; i !== Len; ++i) if (t...
Element: copy event - Web APIs
e">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('copy', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.
toString().toUpperCase()); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element: cut event - Web APIs
ue">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('cut', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.
toString().toUpperCase()); selection.deleteFromDocument(); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
FileException - Web APIs
asic concepts Synchronous APIs do not have error callbacks, which makes it difficult to catch errors. The added complexity of using WebWorkers with this API makes debugging even more challenging. To simplify things a bit, wrap your worker code in a try/catch. When errors occur, forward them to the main app using postMessage() as in the following: function onError(e) { postMEssage('ERROR:' + e.
toString()); } try { //Error is thrown if "log.txt" already exists. var fileEntry = fs.root.getFile('log.txt', {create: true, exclusive:true}0; } catch (e) { onErrror(e); } The sample code was borrowed from HTML5Rocks Attribute Attribute Type Description code unsigned short The most appropriate error code for the condition. Constants Note: Do not rely on ...
FileSystemFileEntry - Web APIs
ite(). function onInitFs(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { console.log('Write completed.'); }; fileWriter.onerror = function(e) { console.log('Write failed: ' + e.
toString()); }; // Create a new Blob and write it to log.txt. var bb = new BlobBuilder(); bb.append('Meow'); fileWriter.write(bb.getBlob('text/plain')); }, errorHandler); }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler); Specifications Specification Status Comment File and Directory Entr...
HTMLAnchorElement - Web APIs
ill assume it is obsolete. HTMLAnchorElement.shape Is a DOMString representing the shape of the active area. Methods Inherits methods from its parent, HTMLElement, and implements those from HTMLHyperlinkElementUtils. HTMLElement.blur() Removes the keyboard focus from the current element. HTMLElement.focus() Gives the keyboard focus to the current element. HTMLHyperlinkElementUtils.
toString() Returns a USVString containing the whole URL. It is a synonym for HTMLHyperlinkElementUtils.href, though it can't be used to modify the value. The blur() and focus() methods are inherited from HTMLElement from HTML5 on, but were defined on HTMLAnchorElement in DOM Level 2 HTML and earlier specifications. Specifications Specification Status Comment HTML Living Standa...
HTMLAreaElement - Web APIs
en the linked resource. HTMLAreaElement.type Is a DOMString that reflects the type HTML attribute, indicating the MIME type of the linked resource. HTMLHyperlinkElementUtils.username Is a USVString containing the username specified before the domain name. Methods Inherits methods from its parent, HTMLElement, and implements those from HTMLHyperlinkElementUtils. HTMLHyperlinkElementUtils.
toString() Returns a USVString containing the whole URL of the script executed in the Worker. It is a synonym for HTMLHyperlinkElementUtils.href. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLAreaElement' in that specification. Living Standard The following property has been added: download. Technically, the URL-related propert...
HTMLHyperlinkElementUtils - Web APIs
username specified before the domain name. HTMLHyperlinkElementUtils.password This is a USVString containing the password specified before the domain name. HTMLHyperlinkElementUtils.origin Read only This returns a USVString containing the origin of the URL (that is its scheme, its domain and its port). Methods Note: This interface doesn't inherit any method. HTMLHyperlinkElementUtils.
toString() This returns a USVString containing the whole URL. It is a synonym for HTMLHyperlinkElementUtils.href, though it can't be used to modify the value. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils' in that specification. Living Standard Initial definition ...
Timing element visibility with the Intersection Observer API - Web APIs
ue of its totalViewTime, converted into minutes and seconds. This is handled by passing the ad's element into the drawAdTimer() function: function drawAdTimer(adBox) { let timerBox = adBox.querySelector(".timer"); let totalSeconds = adBox.dataset.totalViewTime / 1000; let sec = Math.floor(totalSeconds % 60); let min = Math.floor(totalSeconds / 60); timerBox.innerText = min + ":" + sec.
toString().padStart(2, "0"); } This code finds the ad's timer using its ID, "timer", and computes the number of seconds elapsed by dividing the ad's totalViewTime by 1000. Then it calculates the number of minutes and seconds elapsed before setting the timer's innerText to a string representing that time in the form m:ss. The String.padStart() method is used to ensure that the number of seconds is padded ...
Location - Web APIs
ds the current URL, like the Refresh button. Location.replace() Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the assign() method and setting the href property is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it. Location.
toString() Returns a USVString containing the whole URL. It is a synonym for HTMLHyperlinkElementUtils.href, though it can't be used to modify the value. Examples // Create anchor element and use href property for the purpose of this example // A more correct alternative is to browse to the URL and use document.location or window.location var url = document.createElement('a'); url.href = 'https://deve...
PluginArray - Web APIs
].name; newRow.insertCell().textContent = navigator.plugins[i].filename; newRow.insertCell().textContent = navigator.plugins[i].description; newRow.insertCell().textContent = navigator.plugins[i].version?navigator.plugins[i].version:""; } The following example displays information about the installed plugin(s). ...
Using Pointer Events - Web APIs
awing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorForTouch(touch) { var r = touch.pointerId % 16; var g = Math.floor(touch.pointerId / 3) % 16; var b = Math.floor(touch.pointerId / 7) % 16; r = r.
toString(16); // make it a hex digit g = g.
toString(16); // make it a hex digit b = b.
toString(16); // make it a hex digit var color = "#" + r + g + b; log("color for touch with identifier " + touch.pointerId + " = " + color); return color; } The result from this function is a string that can be used when calling <canvas> functions to set drawing colors. For example, for a PointerEvent.pointer...
RTCDataChannel.binaryType - Web APIs
er objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values. var dc = peerConnection.createDataChannel("Binary"); dc.binaryType = "arraybuffer"; dc.onmessage = function(event) { let byteArray = new Uint8Array(event.data); let hexString = ""; byteArray.forEach(function(byte) { hexString += byte.
toString(16) + " "; }); }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.binaryType' in that specification. Candidate Recommendation Initial specification. ...
Range - Web APIs
ent. Range.insertNode() Insert a Node at the start of a Range. Range.surroundContents() Moves content of a Range into a new Node. Range.compareBoundaryPoints() Compares the boundary points of the Range with another Range. Range.cloneRange() Returns a Range object with boundary points identical to the cloned Range. Range.detach() Releases the Range from use to improve performance. Range.
toString() Returns the text of the Range. Range.compareNode() Returns a constant representing whether the Node is before, after, inside, or surrounding the range. Range.comparePoint() Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the Range. Range.createContextualFragment() Returns a DocumentFragment created from a given string of code. Range.getBoundingClie...
Selection.setBaseAndExtent() - Web APIs
Note: You can find this example on GitHub (see it live also.) Specifications Specification Status Comment Selection APIThe definition of 'Selection.setBaseAndExtent()' in ...
Touch events - Web APIs
ng look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorForTouch(touch) { var r = touch.identifier % 16; var g = Math.floor(touch.identifier / 3) % 16; var b = Math.floor(touch.identifier / 7) % 16; r = r.
toString(16); // make it a hex digit g = g.
toString(16); // make it a hex digit b = b.
toString(16); // make it a hex digit var color = "#" + r + g + b; console.log("color for touch with identifier " + touch.identifier + " = " + color); return color; } The result from this function is a string that can be used when calling <canvas> functions to set drawing colors. For example, for a Touch.ident...
URL.toJSON() - Web APIs
The toJSON() method of the URL interface returns a USVString containing a serialized version of the URL, although in practice it seems to have the same effect as URL.
toString(). Note: This feature is available in Web Workers. Syntax const href = url.toJSON() Return value A USVString. Examples const url = new URL("/docs/Web/API/URL/
toString"); url.toJSON(); // should return the URL as a string Specifications Specification Status Comment URLThe definition of 'toJSON()' in that specification. Living Standard Initial definition. ...
URLSearchParams.sort() - Web APIs
en key/value pairs with equal keys will be preserved). Note: This feature is available in Web Workers. Syntax searchParams.sort(); Parameters None. Return value undefined. Examples // Create a test URLSearchParams object var searchParams = new URLSearchParams("c=4&a=2&b=3&a=1"); // Sort the key/value pairs searchParams.sort(); // Display the sorted query string console.log(searchParams.
toString()); The result is: a=2&a=1&b=3&c=4 Specifications Specification Status Comment URLThe definition of 'sort()' in that specification. Living Standard Initial definition ...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
es what percentage of frames have been dropped. That value is then presented in an element for the user's reference. var videoElem = document.getElementById("my_vid"); var percentElem = document.getElementById("percent"); var quality = videoElem.getVideoPlaybackQuality(); var dropPercent = (quality.droppedVideoFrames/quality.totalVideoFrames)*100; percentElem.innerText = Math.trunc(dropPercent).
toString(10); Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.droppedVideoFrames' in that specification. Editor's Draft Initial definition. ...
Writing a WebSocket server in Java - Web APIs
ack as value of Sec-WebSocket-Accept response header as part of a HTTP response. if (get.find()) { Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); match.find(); byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: " + Base64.getEncoder().encode
ToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8"))) + "\r\n\r\n").getBytes("UTF-8"); out.write(response, 0, response.length); Decoding messages After a successful handshake, client can send messages to the server, but now these are encoded. If we send "abcdef", we get these bytes: 129 134 167 225...
Using Web Workers - Web APIs
ndow.onload = function() { document.worker.postMessage(''); }; </script> </head> <body><div id="logDisplay"></div></body> </html> The embedded worker is now nested into a new custom document.worker property. It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example: function fn2workerURL(fn) { var blob = new Blob(['('+fn.
toString()+')()'], {type: 'application/javascript'}) return URL.createObjectURL(blob) } Further examples This section provides further examples of how to use web workers. Performing computations in the background Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibon...
Window.name - Web APIs
also been used in some frameworks for providing cross-domain messaging (e.g., SessionVars and Dojo's dojox.io.windowName) as a more secure alternative to JSONP. Modern web applications hosting sensitive data should, however, not rely on window.name for cross-domain messaging but instead utilize the postMessage API. window.name will convert all values to their string representations by using the
toString method. Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.name' in that specification. Living Standard HTML5The definition of 'Window.name' in that specification. Recommendation ...
WindowOrWorkerGlobalScope.btoa() - Web APIs
se units, but many other characters don't. Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which each character occupies only one byte. So if you pass a string into btoa() containing characters that occupy more than one byte, you will get an error, because this is not considered binary data: const ok = "a"; console.log(ok.codePointAt(0).
toString(16)); // 61: occupies < 1 byte const notOK = "?" console.log(notOK.codePointAt(0).
toString(16)); // 2713: occupies > 1 byte console.log(btoa(ok)); // YQ== console.log(btoa(notOK)); // error If you need to encode Unicode text as ASCII using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. For example: // convert a Unicode string to a string in...
WorkerLocation - Web APIs
containing a '?' followed by the parameters of the URL of the script executed in the Worker. URLUtilsReadOnly.hash Read only Is a DOMString containing a '#' followed by the fragment identifier of the URL of the script executed in the Worker. Methods The WorkerLocation interface doesn't inherit any method, but implements methods defined in the URLUtilsReadOnly interface. URLUtilsReadOnly.
toString() Returns a DOMString containing the whole URL of the script executed in the Worker. It is a synonym for URLUtilsReadOnly.href. Specifications Specification Status Comment HTML Living StandardThe definition of 'WorkerLocation' in that specification. Living Standard ...
XMLDocument.async - Web APIs
document.async can be set to indicate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
XMLDocument.load() - Web APIs
& Save module. Can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). As of at least Gecko 1.9, this no longer supports cross-site loading of documents (Use XMLHttpRequest or fetch() instead). Examples var xmlDoc = document.implementation.createDocument("", "test", null); function documentLoaded (e) { alert(new XMLSerializer().serialize
ToString(e.target)); // Gives querydata.xml contents as string } xmlDoc.addEventListener("load", documentLoaded, false); xmlDoc.load('querydata.xml'); See also the load sample in the XML tests directory. (To test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the LXR-generated page, which will serve the text.xml file as HTML.) Spec...
Using the slider role - Accessibility
="Monday"> </div> </div> The code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var updateSlider = function (newValue) { var handle = document.getElementById("day-handle"); handle.setAttribute("aria-valuenow", newValue.
toString()); handle.setAttribute("aria-valuetext", dayNames[newValue]); }; Working Examples: Slider example Notes ARIA attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation Related ARIA techniques Compatibility TBD: Add support information for common UA and AT product combinations Additional resources WAI-ARIA specification for the sli...
Box-shadow generator - CSS: Cascading Style Sheets
eturn; if (value[0] === '#') value = value.slice(1, value.length); if (value.length === 3) value = value.replace(/([0-9A-F])([0-9A-F])([0-9A-F])/i,"$1$1$2$2$3$3"); this.r = parseInt(value.substr(0, 2), 16); this.g = parseInt(value.substr(2, 2), 16); this.b = parseInt(value.substr(4, 2), 16); this.alpha = 1; } Color.prototype.getHexa = function getHexa() { var r = this.r.
toString(16); var g = this.g.
toString(16); var b = this.b.
toString(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.toUpperCase(); } Color.prototype.getRGBA = function getRGBA() { var rgb = "(" + this.r + ", " + this.g + ", " + this.b; var a = ''; var v = ''; if (this.a !== 1) { a = 'a'; ...
Color picker tool - CSS: Cascading Style Sheets
) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / X; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== Get Methods ==========*/ Color.prototype.getHexa = function getHexa() { var r = this.r.
toString(16); var g = this.g.
toString(16); var b = this.b.
toString(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.toUpperCase(); }; Color.prototype.getRGBA = function getRGBA() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parseFloat(this.a); if ...
Linear-gradient Generator - CSS: Cascading Style Sheets
) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / X; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== Get Methods ==========*/ Color.prototype.getHexa = function getHexa() { var r = this.r.
toString(16); var g = this.g.
toString(16); var b = this.b.
toString(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.toUpperCase(); }; Color.prototype.getRGBA = function getRGBA() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parseFloat(this.a); if ...
Rich-Text Editing in Mozilla - Developer guides
= document.createElement("pre"); oDoc.contentEditable = false; oPre.id = "sourceText"; oPre.contentEditable = true; oPre.appendChild(oContent); oDoc.appendChild(oPre); } else { if (document.all) { oDoc.innerHTML = oDoc.innerText; } else { oContent = document.createRange(); oContent.selectNodeContents(oDoc.firstChild); oDoc.innerHTML = oContent.
toString(); } oDoc.contentEditable = true; } oDoc.focus(); } function printDoc() { if (!validateMode()) { return; } var oPrntWin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oPrntWin.document.open(); oPrntWin.document.write("<!doctype html><html><head><title>Print<\/title><\/head><body onload=\"print();\">" + oDo...
Making content editable - Developer guides
oPre.id = "sourceText"; oPre.contentEditable = true; oPre.appendChild(oContent); oDoc.appendChild(oPre); document.execCommand("defaultParagraphSeparator", false, "div"); } else { if (document.all) { oDoc.innerHTML = oDoc.innerText; } else { oContent = document.createRange(); oContent.selectNodeContents(oDoc.firstChild); oDoc.innerHTML = oContent.
toString(); } oDoc.contentEditable = true; } oDoc.focus(); } function printDoc() { if (!validateMode()) { return; } var oPrntWin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oPrntWin.document.open(); oPrntWin.document.write("<!doctype html><html><head><title>Print<\/title><\/head><body onload=\"print();\">" + oDo...
Equality comparisons and sameness - JavaScript
Object false false ToPrimitive(A) == B ToPrimitive(A) == B ToPrimitive(A) == ToNumber(B) A === B In the above table, ToNumber(A) attempts to convert its argument to a number before comparison. Its behavior is equivalent to +A (the unary + operator). ToPrimitive(A) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of A.
toString and A.valueOf methods on A. Traditionally, and according to ECMAScript, all objects are loosely unequal to undefined and null. But most browsers permit a very narrow class of objects (specifically, the document.all object for any page), in some contexts, to act as if they emulate the value undefined. Loose equality is one such context: null == A and undefined == A evaluate to true if, and only i...
Grammar and types - JavaScript
r foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and allow object-based design to benefit from some of the same conveniences. var obj = { // __proto__ __proto__: theProtoObj, // Shorthand for 'handler: handler' handler, // Methods
toString() { // Super calls return 'd ' + super.
toString(); }, // Computed (dynamic) property names [ 'prop_' + (() => 42)() ]: 42 }; RegExp literals A regex literal (which is defined in detail later) is a pattern enclosed between slashes. The following is an example of a regex literal. var re = /ab+c/; String literals A string literal is zero or more characters enclosed in dou...
Working with objects - JavaScript
that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.
toString() method, and use this result string as the new key. You can also access properties by using a string value that is stored in a variable: var propertyName = 'make'; myCar[propertyName] = 'Ford'; propertyName = 'model'; myCar[propertyName] = 'Mustang'; You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the f...
TypeError: X.prototype.y called on incompatible type - JavaScript
The JavaScript exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function. Message TypeError: 'this' is not a Set object (EdgE) TypeError: Function.prototype.
toString called on incompatible object (Firefox) TypeError: Function.prototype.bind called on incompatible target (Firefox) TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome) TypeError: Bind must be called on a function (Chrome) Error type TypeError What went wrong? When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. This issue can arise when using the Function.prototype.call() or Function.prototype.a...
RangeError: invalid date - JavaScript
or Date.parse(). Examples Invalid cases Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return NaN. However, depending on the implementation, non-conforming ISO format strings, may also throw RangeError: invalid date, like the following cases in Firefox: new Date('foo-bar 2014'); new Date('2014-25-23').toISOString(); new Date('foo-bar 2014').
toString(); This, however, returns NaN in Firefox: Date.parse('foo-bar 2014'); // NaN For more details, see the Date.parse() documentation. Valid cases new Date('05 October 2011 14:48 UTC'); new Date(1317826080); // Unix Time Stamp for 05 October 2011 14:48:00 UTC ...
Array.prototype.reduce() - JavaScript
k < len && !(k in o)) { k++; } // 3. If len is 0 and initialValue is not present, // throw a TypeError exception. if (k >= len) { throw new TypeError( 'Reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8. Repeat, while k < len while (k < len) { // a. Let Pk be !
ToString(k). // b. Let kPresent be ? HasProperty(O, Pk). // c. If kPresent is true, then // i. Let kValue be ? Get(O, Pk). // ii. Let accumulator be ? Call( // callbackfn, undefined, // << accumulator, kValue, k, O >>). if (k in o) { value = callback(value, o[k], k, o); } // d. Increase k by 1. ...
Array.prototype.every() - JavaScript
passing the this // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method // of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== 'function' && Object.prototype.
toString.call(callbackfn) !== '[object Function]') { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be
ToString(k). // This is implicit for LHS oper...
Array.prototype.find() - JavaScript
edicate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be !
ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return kValue. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return kValue; } // e. Increase k by 1. k++; } // 7. Return undefined. return undef...
Array.prototype.findIndex() - JavaScript
ate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be !
ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return k. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return k; } // e. Increase k by 1. k++; } // 7. Return -1. return -1; }, configu...
Array.prototype.indexOf() - JavaScript
fromIndex); else let n be 0. var n = fromIndex | 0; // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len for (; k < len; k++) { // a. Let Pk be
ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of o with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of o with the argument
ToString(k). ...
Array.isArray() - JavaScript
herwise, false is. See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. Polyfill Running the following code before any other code will create Array.isArray() if it's not natively available. ...
Array.prototype.map() - JavaScript
gth > 1) { T = arguments[1]; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be
ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. ...
BigInt64Array - JavaScript
w BigUint64Array from the given start and end element index. BigInt64Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). BigInt64Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). BigInt64Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). BigInt64Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a BigInt64Array // From a length var bigint64 = new BigInt64Array(2); bigint64[0] = 42n; console.log(bigint64[0]); // 42n console.log...
BigUint64Array - JavaScript
igUint64Array from the given start and end element index. BigUint64Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). BigUint64Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). BigUint64Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). BigUint64Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a BigUint64Array // From a length var biguint64 = new BigUint64Array(2); biguint64[0] = 42n; console.log(biguint64[0]); // 42n conso...
Boolean - JavaScript
/ initial value of true Do not use a Boolean object in place of a Boolean primitive. Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with the value false. This property is legacy and non-standard and should not be used. Constructor Boolean() Creates a new Boolean object. Instance methods Boolean.prototype.
toString() Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.
toString() method. Boolean.prototype.valueOf() Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf() method. Examples Creating Boolean objects with an initial value of false var bNoParam = new Boolean(); var bZero = new Boolean(0); var bNul...
Date.prototype[@@toPrimitive] - JavaScript
value. Syntax Date()[Symbol.toPrimitive](hint); Return value The primitive value of the given Date object. Depending on the argument, the method can return either a string or a number. Description The [@@toPrimitive]() method of the Date object returns a primitive value, that is either of type number or of type string. If hint is "string" or "default", [@@toPrimitive]() tries to call the
toString method. If the
toString property does not exist, it tries to call the valueOf method and if the valueOf does not exist either, [@@toPrimitive]() throws a TypeError. If hint is "number", [@@toPrimitive]() first tries to call valueOf, and if that fails, it calls
toString. JavaScript calls the [@@toPrimitive]() method to convert an object to a primitive value. You rarely need to invoke the [@@toPr...
Date.parse() - JavaScript
nt browsers SpiderMonkey's implementation-specific heuristic can be found in jsdate.cpp. The string "10 06 2014" is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this rough outline on how the parsing works. new Date('10 06 2014'); will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: new Date('foo-bar 2014').
toString(); // returns: "Invalid Date" Date.parse('foo-bar 2014'); // returns: NaN Differences in assumed time zone This section contains implementation-specific behavior that can be inconsistent across implementations. Given a non-standard date string of "March 7, 2014", parse() assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as "2014-03-07"...
Date - JavaScript
caleFormat() Converts a date to a string, using a format string. Date.prototype.toLocaleString() Returns a string with a locality-sensitive representation of this date. Overrides the Object.prototype.toLocaleString() method. Date.prototype.toLocaleTimeString() Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings. Date.prototype.
toString() Returns a string representing the specified Date object. Overrides the Object.prototype.
toString() method. Date.prototype.toTimeString() Returns the "time" portion of the Date as a human-readable string. Date.prototype.toUTCString() Converts a date to a string using the UTC timezone. Date.prototype.valueOf() Returns the primitive value of a Date object. Overrides the Object.prototype.val...
Error.prototype.message - JavaScript
The message property is a human-readable description of the error. Description This property contains a brief description of the error if one is available or has been set. SpiderMonkey makes extensive use of the message property for exceptions. The message property combined with the name property is used by the Error.prototype.
toString() method to create a string representation of the Error. By default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the Error constructor. Examples Throwing a custom error var e = new Error('Could not parse input'); // e.message is 'Could not parse input' throw e; Specifications Specification ECMAScript (ECMA-262)The definition of 'Error.prototy...
Error.prototype.name - JavaScript
The name property represents a name for the type of error. The initial value is "Error". Description By default, Error instances are given the name "Error". The name property, in addition to the message property, is used by the Error.prototype.
toString() method to create a string representation of the error. Examples Throwing a custom error var e = new Error('Malformed input'); // e.name is 'Error' e.name = 'ParseError'; throw e; // e.
toString() would return 'ParseError: Malformed input' Specifications Specification ECMAScript (ECMA-262)The definition of 'Error.prototype.name' in that specification. ...
Error - JavaScript
for the path to the file that raised this error. Error.prototype.lineNumber A non-standard Mozilla property for the line number in the file that raised this error. Error.prototype.columnNumber A non-standard Mozilla property for the column number in the line that raised this error. Error.prototype.stack A non-standard Mozilla property for a stack trace. Instance methods Error.prototype.
toString() Returns a string representing the specified object. Overrides the Object.prototype.
toString() method. Examples Throwing a generic error Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct: try { throw new Error('Whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } Handling...
Float32Array - JavaScript
a new Float32Array from the given start and end element index. Float32Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Float32Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Float32Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Float32Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Float32Array // From a length var float32 = new Float32Array(2); float32[0] = 42; console.log(float32[0]); // 42 console.log(float32...
Float64Array - JavaScript
a new Float64Array from the given start and end element index. Float64Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Float64Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Float64Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Float64Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Float64Array // From a length var float64 = new Float64Array(2); float64[0] = 42; console.log(float64[0]); // 42 console.log(float64...
Function - JavaScript
1[, arg2[, ...argN]]]) Creates a new function which, when called, has its this set to the provided thisArg. Optionally, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called. Function.prototype.call(thisArg[, arg1, arg2, ...argN]) Calls a function and sets its this to the provided value. Arguments can be passed as they are. Function.prototype.
toString() Returns a string representing the source code of the function. Overrides the Object.prototype.
toString method. Examples Difference between Function constructor and function declaration Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own ...
Int16Array - JavaScript
Returns a new Int16Array from the given start and end element index. Int16Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Int16Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Int16Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Int16Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create an Int16Array // From a length var int16 = new Int16Array(2); int16[0] = 42; console.log(int16[0]); // 42 console.log(int16.length); // ...
Int32Array - JavaScript
Returns a new Int32Array from the given start and end element index. Int32Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Int32Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Int32Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Int32Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create an Int32Array // From a length var int32 = new Int32Array(2); int32[0] = 42; console.log(int32[0]); // 42 console.log(int32.length); // ...
Int8Array - JavaScript
y() Returns a new Int8Array from the given start and end element index. Int8Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Int8Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Int8Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Int8Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create an Int8Array // From a length var int8 = new Int8Array(2); int8[0] = 42; console.log(int8[0]); // 42 console.log(int8.length); // 2 conso...
Intl.Locale - JavaScript
rns the script used for writing the particular language used in the locale. Instance methods Intl.Locale.prototype.maximize() Gets the most likely values for the language, script, and region of the locale based on existing values. Intl.Locale.prototype.minimize() Gets the most likely values for the language, script, and region of the locale based on existing values. Intl.Locale.prototype.
toString() Returns the Locale's full locale identifier string. Examples Basic usage At its very simplest, the Intl.Locale constructor takes a locale identifier string as its argument: let us = new Intl.Locale('en-US'); Using the Locale constructor with an options object The constructor also takes an optional configuration object argument, which can contain any of several extension types. For examp...
JSON.parse() - JavaScript
sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); rx_dangerous.lastIndex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charCodeAt(0).
toString(16)).slice(-4) ); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with "()" and "new" // because they can cause invocation, and "=" because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // W...
Number.parseFloat() - JavaScript
ument, it returns NaN. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.parseFloat(string) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the
ToString abstract operation. Leading whitespace in this argument is ignored. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. Polyfill if (Number.parseFloat === undefined) { Number.parseFloat = parseFloat; } Examples Number.parseFloat vs parseFloat This method has the same functionality as the glo...
Number.parseInt() - JavaScript
radix or base. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.parseInt(string,[ radix]) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the
ToString abstract operation. Leading whitespace in this argument is ignored. radix Optional An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful--this does not default to 10! Return value An integer parsed from the given string. If the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be con...
Number.prototype.toFixed() - JavaScript
er. Description toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of numObj is greater or equal to 1e+21, this method simply calls Number.prototype.
toString() and returns a string in exponential notation. Warning: Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false . Examples Using toFixed let numObj = 12345.6789 numObj.toFixed() // Returns '12346': note rounding, no fractional part numObj.toFixed(1) // Returns '12345.7': note roundi...
Number.prototype.toPrecision() - JavaScript
ion Optional An integer specifying the number of significant digits. Return value A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the Number.prototype.toFixed() method, which also applies to toPrecision(). If the precision argument is omitted, behaves as Number.prototype.
toString(). If the precision argument is a non-integer value, it is rounded to the nearest integer. Exceptions RangeError If precision is not between 1 and 100 (inclusive), a RangeError is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. Examples Using toPrecision let numObj = 5.123456 console.log...
Number - JavaScript
presenting the number in fixed-point notation. Number.prototype.toLocaleString([locales [, options]]) Returns a string with a language sensitive representation of this number. Overrides the Object.prototype.toLocaleString() method. Number.prototype.toPrecision(precision) Returns a string representing the number to a specified precision in fixed-point or exponential notation. Number.prototype.
toString([radix]) Returns a string representing the specified object in the specified radix ("base"). Overrides the Object.prototype.
toString() method. Number.prototype.valueOf() Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method. Examples Using the Number object to assign values to numeric variables The following example uses the Number object's pr...
Object.prototype.constructor - JavaScript
/ remains unchanged new Date(), new Error(), new Function(), function () {}, Math, new Number(), 1, // remains unchanged new Object(), {}, new RegExp(), /(?:)/, new String(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = Type types[i] = [types[i].constructor, types[i] instanceof Type, types[i].
toString()] } console.log(types.join('\n')) This example displays the following output (comments added for reference): function Type() {},false, // new Array() function Type() {},false, // [] function Type() {},false,false // new Boolean() function Boolean() { [native code] },false,true ...
Object.prototype.toLocaleString() - JavaScript
locale-specific purposes. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj.toLocaleString() Return value A string representing the object. Description Object's toLocaleString returns the result of calling
toString(). This function is provided to give objects a generic toLocaleString method, even though not all may use it. See the list below. Objects overriding toLocaleString Array: Array.prototype.toLocaleString() Number: Number.prototype.toLocaleString() Date: Date.prototype.toLocaleString() TypedArray: TypedArray.prototype.toLocaleString() BigInt: BigInt.prototype.toLocaleString() Examples Ar...
Object - JavaScript
rty of that object and not inherited through the prototype chain. Object.prototype.isPrototypeOf() Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object. Object.prototype.propertyIsEnumerable() Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set. Object.prototype.toLocaleString() Calls
toString(). Object.prototype.
toString() Returns a string representation of the object. Object.prototype.unwatch() Removes a watchpoint from a property of the object. Object.prototype.valueOf() Returns the primitive value of the specified object. Object.prototype.watch() Adds a watchpoint to a property of the object. Examples Using Object given undefined and null types The following examples st...
Reflect.has() - JavaScript
or not the target has the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
RegExp.prototype.flags - JavaScript
Writable no Enumerable no Configurable yes Description Flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). Polyfill if (RegExp.prototype.flags === undefined) { Object.defineProperty(RegExp.prototype, 'flags', { configurable: true, get: function() { return this.
toString().match(/[gimsuy]*$/)[0]; } }); } Examples Using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.flags' in that specification. ...
RegExp - JavaScript
sticky Whether or not the search is sticky. RegExp.prototype.unicode Whether or not Unicode features are enabled. Instance methods RegExp.prototype.compile() (Re-)compiles a regular expression during execution of a script. RegExp.prototype.exec() Executes a search for a match in its string parameter. RegExp.prototype.test() Tests for a match in its string parameter. RegExp.prototype.
toString() Returns a string representing the specified object. Overrides the Object.prototype.
toString() method. RegExp.prototype[@@match]() Performs match to given string and returns match result. RegExp.prototype[@@matchAll]() Returns all matches of the regular expression against a string. RegExp.prototype[@@replace]() Replaces matches in given string with new substring. RegExp.prototype[@@searc...
String.prototype.normalize() - JavaScript
All canonically equivalent sequences are also compatible, but not vice versa. For example: the code point U+FB00 represents the ligature "ff". It is compatible with two...
String.prototype.padStart() - JavaScript
art. Examples Basic examples 'abc'.padStart(10); // " abc" 'abc'.padStart(10, "foo"); // "foofoofabc" 'abc'.padStart(6,"123465"); // "123abc" 'abc'.padStart(8, "0"); // "00000abc" 'abc'.padStart(1); // "abc" Fixed width string number conversion // Javascript version of: (unsigned) // printf "%0*d" width num function leftFillNum(num, targetLength) { return num.
toString().padStart(targetLength, 0); } const num = 123; console.log(leftFillNum(num, 5)); // expected output: "00123" Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.padStart' in that specification. ...
String.prototype.toUpperCase() - JavaScript
ppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. Examples Basic usage console.log('alphabet'.toUpperCase()); // 'ALPHABET' Conversion of non-string this values to strings This method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = String.prototype.toUpperCase.call({
toString: function
toString() { return 'abcdef'; } }); const b = String.prototype.toUpperCase.call(true); // prints out 'ABCDEF TRUE'. console.log(a, b); Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.toUpperCase' in that specification. ...
String.prototype.valueOf() - JavaScript
The valueOf() method returns the primitive value of a String object. Syntax str.valueOf() Return value A string representing the primitive value of a given String object. Description The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.
toString(). This method is usually called internally by JavaScript and not explicitly in code. Examples Using valueOf() var x = new String('Hello world'); console.log(x.valueOf()); // Displays 'Hello world' Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.valueOf' in that specification. ...
Symbol.for() - JavaScript
[[symbol]] A symbol that is stored globally. Examples Using Symbol.for Symbol.for('foo'); // create a new global symbol Symbol.for('foo'); // retrieve the already created symbol // Same global symbol, but not locally Symbol.for('bar') === Symbol.for('bar'); // true Symbol('bar') === Symbol('bar'); // false // The key is also used as the description var sym = Symbol.for('mario'); sym.
toString(); // "Symbol(mario)" To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: Symbol.for('mdn.foo'); Symbol.for('mdn.bar'); Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.for' in that specification. ...
TypedArray - JavaScript
Returns a new TypedArray from the given start and end element index. TypedArray.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). TypedArray.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). TypedArray.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). TypedArray.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples New is required Starting with ECMAScript 2015, TypedArray constructors must be constructed with the new operator. Calling a TypedArray constructor as a function ...
Uint16Array - JavaScript
urns a new Uint16Array from the given start and end element index. Uint16Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Uint16Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Uint16Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Uint16Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Uint16Array // From a length var uint16 = new Uint16Array(2); uint16[0] = 42; console.log(uint16[0]); // 42 console.log(uint16.length...
Uint32Array - JavaScript
urns a new Uint32Array from the given start and end element index. Uint32Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Uint32Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Uint32Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Uint32Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Uint32Array // From a length var uint32 = new Uint32Array(2); uint32[0] = 42; console.log(uint32[0]); // 42 console.log(uint32.length...
Uint8Array - JavaScript
Returns a new Uint8Array from the given start and end element index. Uint8Array.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Uint8Array.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Uint8Array.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Uint8Array.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Uint8Array // From a length var uint8 = new Uint8Array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2...
Uint8ClampedArray - JavaScript
rray from the given start and end element index. Uint8ClampedArray.prototype.values() Returns a new Array Iterator object that contains the values for each index in the array. See also Array.prototype.values(). Uint8ClampedArray.prototype.toLocaleString() Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString(). Uint8ClampedArray.prototype.
toString() Returns a string representing the array and its elements. See also Array.prototype.
toString(). Uint8ClampedArray.prototype[@@iterator]() Returns a new Array Iterator object that contains the values for each index in the array. Examples Different ways to create a Uint8ClampedArray // From a length var uintc8 = new Uint8ClampedArray(2); uintc8[0] = 42; uintc8[1] = 1337; console.log(uintc8[...
WebAssembly.CompileError - JavaScript
error. Inherited from Error. WebAssembly.CompileError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.CompileError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.CompileError.prototype.toSource() Returns code that could eval to the same error. Inherited from Error. WebAssembly.CompileError.prototype.
toString() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new CompileError instance The following snippet creates a new CompileError instance, and logs its details to the console: try { throw new WebAssembly.CompileError('Hello', 'someFile', 10); } catch (e) { console.log(e instanceof CompileError); // true console.log(e.message); ...
WebAssembly.Global - JavaScript
or WebAssembly.Global() Creates a new Global object. Global instances All Global instances inherit from the Global() constructor's prototype object -- this can be modified to affect all Global instances. Instance properties Global.prototype.constructor Returns the function that created this object's instance. By default this is the WebAssembly.Global() constructor. Global.prototype[@@
toStringTag] The initial value of the @@
toStringTag property is the String value "WebAssembly.Global". Global.prototype.value The value contained inside the global variable -- this can be used to directly set and get the global's value. Instance methods Global.prototype.valueOf() Old-style method that returns the value contained inside the global variable. Examples Creating a new Global instan...
WebAssembly.LinkError - JavaScript
raised this error. Inherited from Error. WebAssembly.LinkError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.LinkError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.LinkError.prototype.toSource() Returns code that could eval to the same error. Inherited from Error. WebAssembly.LinkError.prototype.
toString() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new LinkError instance The following snippet creates a new LinkError instance, and logs its details to the console: try { throw new WebAssembly.LinkError('Hello', 'someFile', 10); } catch (e) { console.log(e instanceof LinkError); // true console.log(e.message); // "H...
WebAssembly.RuntimeError - JavaScript
error. Inherited from Error. WebAssembly.RuntimeError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.RuntimeError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.RuntimeError.prototype.toSource() Returns code that could eval to the same error. Inherited from Error. WebAssembly.RuntimeError.prototype.
toString() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new RuntimeError instance The following snippet creates a new RuntimeError instance, and logs its details to the console: try { throw new WebAssembly.RuntimeError('Hello', 'someFile', 10); } catch (e) { console.log(e instanceof RuntimeError); // true console.log(e.message); ...
eval() - JavaScript
t. If the argument of eval() is not a string, eval() returns the argument unchanged. In the following example, the String constructor is specified and eval() returns a String object rather than evaluating the string. eval(new String('2 + 2')); // returns a String object containing "2 + 2" eval('2 + 2'); // returns 4 You can work around this limitation in a generic fashion by using
toString(). var expression = new String('2 + 2'); eval(expression.
toString()); // returns 4 If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to l...
isNaN() - JavaScript
// Parsing this as a number fails and returns NaN Useful special-case behavior There is a more usage oriented way to think of isNaN(): If isNaN(x) returns false, you can use x in an arithmetic expression not making the ...
in operator - JavaScript
e To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array. let empties = new Array(3).fill(undefined) 2 in empties // returns true Inherited properties The in operator returns true for properties in the prototype chain. (If you want to check for only non-inherited properties, use Object.prototype.hasOwnProperty() instead.) '
toString' in {} // returns true Specifications Specification ECMAScript (ECMA-262)The definition of 'Relational Operators' in that specification. ...
this - JavaScript
not an object, an attempt will be made to convert it to an object. Values null and undefined become the global object. Primitives like 7 or 'foo' will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g. function bar() { console.log(Object.prototype.
toString.call(this)); } bar.call(7); // [object Number] bar.call('foo'); // [object String] bar.call(undefined); // [object global] The bind method ECMAScript 5 introduced Function.prototype.bind(). Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of...
for...in - JavaScript
e is assigned to variable on each iteration. object Object whose non-Symbol enumerable properties are iterated over. Description A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built-in constructors like Array and Object have inherited non-enumerable properties from Object.prototype and String.prototype, such as String's indexOf() method or Object's
toString() method. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). Deleted, added, or modified properties A for...in loop iterates over the properties of an object in an arbitrary order (see the de...
pointer-events - SVG: Scalable Vector Graphics
ect itself --> <rect x="10" y="0" height="10" width="10" fill="black" /> <circle cx="15" cy="5" r="4" fill="white" pointer-events="none" /> </svg> window.addEventListener('mouseup', (e) => { // Let's pick a random color between #000000 and #FFFFFF const color = Math.round(Math.random() * 0xFFFFFF) // Let's format the color to fit CSS requirements const fill = '#' + color.
toString(16).padStart(6,'0') // Let's apply our color in the // element we actually clicked on e.target.style.fill = fill }) As a presentation attribute, it can be applied to any element but it is mostly relevant only on the following twenty-three elements: <a>, <circle>, <clipPath>, <defs>, <ellipse>, <foreignObject>, <g>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyl...
<script> - SVG: Scalable Vector Graphics
ncies, like it uses the href attribute instead of src and it doesn't support ECMAScript modules so far (See browser compatibility below for details) html,body,svg { height:100% } <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <script> // <![CDATA[ window.addEventListener('DOMContentLoaded', () => { function getColor () { const R = Math.round(Math.random() * 255).
toString(16).padStart(2,'0') const G = Math.round(Math.random() * 255).
toString(16).padStart(2,'0') const B = Math.round(Math.random() * 255).
toString(16).padStart(2,'0') return `#${R}${G}${B}` } document.querySelector('circle').addEventListener('click', (e) => { e.target.style.fill = getColor() }) }) // ]]> </script> <circle cx="5" cy="5" r="4" /> </svg> ...
Exported WebAssembly functions - WebAssembly
ion to being wrappers for WebAssembly functions. If you load the above example in a WebAssembly-supporting browser, and run the following lines in your console: var testFunc = otherTable.get(0); typeof testFunc; you'll get the result function returned. You can then go on to do pretty much anything to this function that you can do to other functions in JavaScript -- call(), bind(), etc. testFunc.
toString() returns an interesting result: function 0() { [native code] } This gives you more of an idea of its wrapper-type nature. Some other particulars to be aware of with exported WebAssembly functions: Their length property is the number of declared arguments in the wasm function signature. Their name property is the
toString() result of the function's index in the wasm module. If you try...