Search completed in 1.12 seconds.
926 results for "prototype":
Your results are loading. Please wait...
Object.prototype.isPrototypeOf() - JavaScript
the isprototypeof() method checks if an object exists in another object's prototype chain. 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. isprototypeof() differs from the instanceof operator. in the expression "object instanceof afunction", the object prototype chain is checked against afunction.prototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown i...
... afunction", the object prototype chain is checked against afunction.prototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown if prototypeobj is undefined or null. description the isprototypeof() method allows you to check whether or not an object exists within another object's prototype chain. ...
...whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown if prototypeobj is undefined or null. description the isprototypeof() method allows you to check whether or not an object exists within another object's prototype chain. ...
...And 13 more matches
Inheritance and the prototype chain - JavaScript
javascript is a bit confusing for developers experienced in class-based languages (like java or c++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in es2015, but is syntactical sugar, javascript remains prototype-based). when it comes to inheritance, javascript only has one construct: objects. each object has a private property which holds a link to another object called its prototype. that prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. by definition, null has no prototype, and acts as the final link in this prototype chain. nearly all objects in javascript are instances of object which sits on the top of a prototype chain. while this confusion is often considered to be one of ...
...ototype chain. nearly all objects in javascript are instances of object which sits on the top of a prototype chain. while this confusion is often considered to be one of javascript's weaknesses, the prototypal inheritance model itself is, in fact, more powerful than the classic model. it is, for example, fairly trivial to build a classic model on top of a prototypal model. inheritance with the prototype chain inheriting properties javascript objects are dynamic "bags" of properties (referred to as own properties). javascript objects have a link to a prototype object. ...
...it is, for example, fairly trivial to build a classic model on top of a prototypal model. inheritance with the prototype chain inheriting properties javascript objects are dynamic "bags" of properties (referred to as own properties). javascript objects have a link to a prototype object. when trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached. following the ecmascript standard, the notation someobject.[[prototype]] is used to designate the prototype of someobject. ...
...And 64 more matches
Object prototypes - Learn web development
previous overview: objects next prototypes are the mechanism by which javascript objects inherit features from one another. in this article, we explain how prototype chains work and look at how the prototype property can be used to add methods to existing constructors. note: this article covers traditional javascript constructors and classes. in the next article, we talk about the modern way of doing things, which provides easier syntax to achieve the same things — see ecmascript 2015 classes. prerequisites: understanding javascript functions, familiarity with javascript basics (see first steps and building blocks), and oojs basics (see introduction to objects). ...
...s. in the next article, we talk about the modern way of doing things, which provides easier syntax to achieve the same things — see ecmascript 2015 classes. prerequisites: understanding javascript functions, familiarity with javascript basics (see first steps and building blocks), and oojs basics (see introduction to objects). ...
...rticle, we talk about the modern way of doing things, which provides easier syntax to achieve the same things — see ecmascript 2015 classes. prerequisites: understanding javascript functions, familiarity with javascript basics (see first steps and building blocks), and oojs basics (see introduction to objects). ...
...And 31 more matches
Function.prototype.bind() - JavaScript
een constructed. the provided this value is ignored, while prepended arguments are provided to the emulated function. polyfill because older browsers are generally also slower browsers, it is far more critical than most people recognize to create performance polyfills to make the browsing experience in outdated browsers slightly less horrible. thus, presented below are two options for function.prototype.bind() polyfills: the first one is much smaller and more performant, but does not work when using the new operator. the second one is bigger and less performant, but it permits some usage of the new operator on bound functions. generally, in most code it's very rare to see new used on a bound function, so it is generally best to go with the first option. // does not work with `new (funca.
...is much smaller and more performant, but does not work when using the new operator. the second one is bigger and less performant, but it permits some usage of the new operator on bound functions. generally, in most code it's very rare to see new used on a bound function, so it is generally best to go with the first option. ...
... work when using the new operator. the second one is bigger and less performant, but it permits some usage of the new operator on bound functions. generally, in most code it's very rare to see new used on a bound function, so it is generally best to go with the first option. ...
...And 27 more matches
JavaScript-DOM Prototypes in Mozilla
prototype setup on an xpconnect wrapped dom node in mozilla when a dom node is accessed from javascript in mozilla, the native c++ dom node is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node. when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (nsiclassinfo), the jsobject is a more or less empty jsobject which is not really that special. ...
...on of the dom node. when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (nsiclassinfo), the jsobject is a more or less empty jsobject which is not really that special. all the methods that are supposed to show up on this jsobject are actually not properties of the object itself, but rather properties of the prototype of the jsobject for the wrapper (unless the c++ object's class info has the flag nsixpcscriptable::dont_share_prototype set, but lets assume that's not the case here). as an example of this let's look at an html image element in a document. var obj = document.images[0]; here, obj will not really have any properties (except for the standard jsobject properties such as constructor, and the non-...
...criptable::dont_share_prototype set, but lets assume that's not the case here). as an example of this let's look at an html image element in a document. var obj = document.images[0]; here, obj will not really have any properties (except for the standard jsobject properties such as constructor, and the non-standard __parent__, __proto__, etc.), all the dom functionality of obj comes from obj's prototype (obj.__proto__) that xpconnect sets up when exposing the first image in document to javascript. here are a few of the properties of obj's prototype: obj.__proto__ parentnode (getter function) src (getter and setter functions) getelementsbytagname (function) text_node (number property, constant) ... all those properties come from the interfaces that the c++ image object (nshtmlimageel...
...And 25 more matches
Object.setPrototypeOf() - JavaScript
because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). ...
... because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). ...
...] property) of a specified object to another object or null. warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, currently a very slow operation in every browser and javascript engine. in addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the object.setprototypeof(...) statement, but may extend to any code that has access to any object whose [[prototype]] has been altered. because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[prototype]] of an object. in...
...And 20 more matches
Object.prototype.__proto__ - JavaScript
warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, a very slow operation, in every browser and javascript engine. the effects on the performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[prototype]] has been altered. if you care about performance you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). ...
...nce are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[prototype]] has been altered. if you care about performance you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). warning: while object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ecmascript 2015 specification as a legacy feature to ensure compatibility for web browsers. ...
... the use of __proto__ is controversial and discouraged. ...
...And 12 more matches
Reflect.getPrototypeOf() - JavaScript
the static reflect.getprototypeof() method is almost the same method as object.getprototypeof(). it returns the prototype (i.e. the value of the internal [[prototype]] property) of the specified 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 reflect.getprototypeof(target) parameters target the target object of which to get the prototype. return value the prototype of the given object. if there are no inherited properties, null is returned. exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method returns the prototype (i.e. the value of the internal [[...
...nd us a pull request. syntax reflect.getprototypeof(target) parameters target the target object of which to get the prototype. return value the prototype of the given object. if there are no inherited properties, null is returned. exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method returns the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. ...
... target the target object of which to get the prototype. return value the prototype of the given object. if there are no inherited properties, null is returned. exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method returns the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. ...
...And 12 more matches
TextEncoder.prototype.encodeInto() - Web APIs
this is potentially more performant than the older encode() method especially when the target buffer is a view into a wasm heap. syntax b1 = encoder.encodeinto(string, uint8array); parameters string is a usvstring containing the text to encode. uint8array is a uint8array object instance to place the resulting utf-8 encoded text into. return value a textencoderencodeintoresult dictionary, which contains two members: read the number of utf-16 units of code from the source that has been converted over to utf-8. ...
...ength if uint8array did not have enough space. written the number of bytes modified in the destination uint8array. the bytes written are guaranteed to form complete utf-8 byte sequences. encode into a specific position encoder.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. var encoder = new textencoder; function encodeintoatposition(string, u8array, position) { return encoder.encodeinto(string, position ? u8array.subarray(position|0) : u8array); } var u8array = new uint8array(8); encodeintoatposition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 buffer sizing to convert a javascript string s, th...
...w uint8array(string.length); let encodedresults = textencoder.encodeinto(string, utf8); resultpara.textcontent += 'bytes read: ' + encodedresults.read + ' | bytes written: ' + encodedresults.written + ' | encoded result: ' + utf8; polyfill the polyfill below may be a bit long because of the switch cases and utilization of native textencoder.prototype.encode in safari when available, but it is well worth the length because of the gains in performance. (function(window){ "use strict"; var log = math.log; var ln2 = math.ln2; var clz32 = math.clz32 || function(x) {return 31 - log(x >>> 0) / ln2 | 0}; var fromcharcode = string.fromcharcode; var patchedu8array = window.uint8array || array; var textencoderprototype = tex...
...And 7 more matches
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
the javascript warning about string generics occurs in firefox versions prior to 68. string generics have been removed starting with firefox 68. ...
... the javascript warning about string generics occurs in firefox versions prior to 68. string generics have been removed starting with firefox 68. ...
...ascript warning about string generics occurs in firefox versions prior to 68. string generics have been removed starting with firefox 68. ...
...And 7 more matches
Object.prototype.constructor - JavaScript
,false,/(?:)/ // /(?:)/ function type() {},false, // new string() function string() { [native code] },false,test // 'test' changing the constructor of a function mostly this property is used for defining a function as a function-constructor with further calling it with new and prototype-inherits chain. function parent() { /* ... */ } parent.prototype.parentmethod = function parentmethod() {} function child() { parent.call(this) // make sure everything is initialized properly } child.prototype = object.create(parent.prototype) // re-define child prototype to parent prototype child.prototype.constructor = child // return original constructor to child but when do we need to ...
...ast line here? unfortunately, the answer is: it depends. let's try to define the cases in which re-assignment of the original constructor will play a major role, and when it will be one superfluous line of code. take the following case: the object has the create() method to create itself. function parent() { /* ... */ } function createdconstructor() { parent.call(this) } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // typeerror undefined is not a function since constructor === parent in the example above the exception will be shown since the constructor links to parent. to avoid this, just assign the necessary constructor you are going t...
...ew this.constructor() } new createdconstructor().create().create() // typeerror undefined is not a function since constructor === parent in the example above the exception will be shown since the constructor links to parent. to avoid this, just assign the necessary constructor you are going to use. function parent() { /* ... */ } function createdconstructor() { /* ... */ } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.constructor = createdconstructor // sets the correct constructor for future use createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // it's pretty fine ok, now it's pretty clear why changing the constructor can be useful. let's consider one more cas...
...And 6 more matches
Object.prototype.toString() - JavaScript
e', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // returns [object object] the following code creates and assigns dogtostring() to override the default tostring() method. this function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;". ...
...reates and assigns dogtostring() to override the default tostring() method. this function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;". ...
...ex} ${this.color} ${this.breed}`; } with the preceding code in place, any time thedog is used in a string context, javascript automatically calls the dogtostring() function, which returns the following string: "dog gabby is a female chocolate lab" using tostring() to detect object class tostring() can be used with every object and (by default) allows you to get its class. ...
...And 6 more matches
Function.prototype.apply() - JavaScript
); min = math.min(submin, min); } return min; } let min = minofarray([5, 6, 2, 3, 7]); using apply to chain constructors you can use apply to chain constructors for an object (similar to java). in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. ...
...farray([5, 6, 2, 3, 7]); using apply to chain constructors you can use apply to chain constructors for an object (similar to java). in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. ...
...able you to use an array-like object with a constructor instead of an arguments list. function.prototype.construct = function(aargs) { let onew = object.create(this.prototype); this.apply(onew, aargs); return onew; }; note: the object.create() method used above is relatively new. ...
...And 5 more matches
Promise.prototype.catch() - JavaScript
this means that you have to provide an onrejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}). 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. ...
...tch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. this function has one argument: reason the rejection reason. the promise returned by catch() is rejected if onrejected throws an error or returns a promise which is itself rejected; otherwise, it is resolved. return value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler. returns the value of that call, which is a promise. note the examples below are throwing instances of error. this is considered good practice in contrast to throwing strings; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or ...
...at call, which is a promise. note the examples below are throwing instances of error. this is considered good practice in contrast to throwing strings; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information like stack traces. ...
...And 5 more matches
handler.getPrototypeOf() - JavaScript
the handler.getprototypeof() method is a trap for the [[getprototypeof]] internal 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. syntax const p = new proxy(obj, { getprototypeof(target) { ... } }); parameters the following parameter is passed to the getprototypeof() method. this is bound to the handler. target the target object. return value the getprototypeof() method must return an object or null. ...
...send us a pull request. syntax const p = new proxy(obj, { getprototypeof(target) { ... } }); parameters the following parameter is passed to the getprototypeof() method. this is bound to the handler. target the target object. return value the getprototypeof() method must return an object or null. description interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a typeerror: getprototypeof() method must return an object or null. if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target). examples basic usage const obj = ...
...ct.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a typeerror: getprototypeof() method must return an object or null. if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target). ...
...And 5 more matches
Function.prototype.toString() - JavaScript
le 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. ...
...t 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. ...
...he 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. ...
...And 4 more matches
handler.setPrototypeOf() - JavaScript
the handler.setprototypeof() method is a trap for object.setprototypeof(). 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 const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method. this is bound to the handler. target the target object. prototype the object's new prototype or null. return value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). intercepti...
...() method. this is bound to the handler. target the target object. prototype the object's new prototype or null. return value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). ...
...a trap for object.setprototypeof(). interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception. approach 1: returning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an operation tha...
...And 4 more matches
TypedArray.prototype.fill() - JavaScript
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.fill(value[, start = 0[, end = this.length]]) parameters value value to fill the typed array with. start optional. start index. defaults to 0. end optional. ...
...end arguments are optional with default values of 0 and the length of the this object. if start is negative, it is treated as length+start where length is the length of the array. if end is negative, it is treated as length+end. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. ...
...bject. if start is negative, it is treated as length+start where length is the length of the array. if end is negative, it is treated as length+end. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. use the following "polyfill" along with the array.prototype.fill() polyfill. ...
...And 4 more matches
JS_LinkConstructorAndPrototype
this article covers features introduced in spidermonkey 17 set up ctor.prototype = proto and proto.constructor = ctor with the right property flags. syntax bool js_linkconstructorandprototype(jscontext *cx, js::handle<jsobject*> ctor, js::handle<jsobject*> proto); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handle&lt;jsobject*&gt; pointer to the constructor object. proto js::handle&lt;jsobject*&gt; pointer to the prototype object. ...
...on cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handle&lt;jsobject*&gt; pointer to the constructor object. proto js::handle&lt;jsobject*&gt; pointer to the prototype object. ...
...scontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handle&lt;jsobject*&gt; pointer to the constructor object. proto js::handle&lt;jsobject*&gt; pointer to the prototype object. ...
...And 3 more matches
JS_SetPrototype
set a javascript object's prototype. syntax bool js_setprototype(jscontext *cx, js::handleobject obj, js::handleobject proto); name type description cx jscontext * the context in which to set the object's prototype. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to modify. proto js::handleobject the object to set as the new prototype of obj. description js_setprototype sets the prototype object for a specified object. a prototype object provides properties that are shared by similar js object instances. ...
...adsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to modify. proto js::handleobject the object to set as the new prototype of obj. description js_setprototype sets the prototype object for a specified object. a prototype object provides properties that are shared by similar js object instances. ordinarily you set a prototype for an object when you create the object with js_newobject, but if you do not set a prototype at that time, you can later call js_setprototype to do so. obj is a pointer to an existing js object, and proto is a pointer to second existing object upon which the first object is to be based. on success, js_setprototype returns true. otherwise it returns false. take care not to create a circularly-lin...
...ct when you create the object with js_newobject, but if you do not set a prototype at that time, you can later call js_setprototype to do so. obj is a pointer to an existing js object, and proto is a pointer to second existing object upon which the first object is to be based. on success, js_setprototype returns true. otherwise it returns false. take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite loop. ...
...And 3 more matches
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. ...
... 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. ...
...on "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. ...
...And 3 more matches
Array.prototype.forEach() - JavaScript
e is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach() loop other than by throwing an exception. if you need such behavior, the foreach() method is the wrong tool. early termination may be accomplished with: a simple for loop a for...of / for...in loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. kindly make sure you are aware of the implications while using pr...
...onsole.log('a[' + index + '] = ' + element) } // notice that index 2 is skipped, since there is no item at // that position in the array... [2, 5, , 9].foreach(logarrayelements) // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 using thisarg the following (contrived) example updates an object's properties from each entry in the array: function counter() { this.sum = 0 this.count = 0 } counter.prototype.add = function(array) { array.foreach((entry) => { this.sum += entry ++this.count }, this) // ^---- note } const obj = new counter() obj.add([2, 5, 9]) obj.count // 3 obj.sum // 16 since the thisarg parameter (this) is provided to foreach(), it is passed to callback each time it's invoked. the callback uses it as its this value. note: if passing the callback function uses an ar...
...s it as its this value. note: if passing the callback function uses an arrow function expression, the thisarg parameter can be omitted, since all arrow functions lexically bind the this value. an object copy function the following code creates a copy of a given object. there are different ways to create a copy of an object. ...
...And 3 more matches
Array.prototype.indexOf() - JavaScript
rom front to back. if the provided index is 0, then the whole array will be searched. default: 0 (entire array is searched). return value the first index of the element in the array; -1 if not found. description indexof() compares searchelement to elements of the array using strict equality (the same method used by the === or triple-equals operator). note: for the string method, see string.prototype.indexof(). polyfill indexof() was added to the ecma-262 standard in the 5th edition; as such it may not be present in all browsers. you can work around this by utilizing the following code at the beginning of your scripts. this will allow you to use indexof() when there is still no native support. this algorithm matches the one specified in ecma-262, 5th edition, assuming typeerror and math.a...
...l no native support. this algorithm matches the one specified in ecma-262, 5th edition, assuming typeerror and math.abs() have their original values. // this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search. other parts are merely cosmetic conciseness. // whether it is actually faster remains to be seen. ...
...lgorithm matches the one specified in ecma-262, 5th edition, assuming typeerror and math.abs() have their original values. // this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search. other parts are merely cosmetic conciseness. // whether it is actually faster remains to be seen. ...
...And 3 more matches
Array.prototype.toLocaleString() - JavaScript
se strings are separated by a locale-specific string (such as a comma “,”). syntax arr.tolocalestring([locales[, options]]); parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional an object with configuration properties, for numbers see number.prototype.tolocalestring(), and for dates see date.prototype.tolocalestring(). return value a string representing the elements of the array. polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!array.prototype.tolocalestring) { object.defineproperty(array.prototype, 'tolocalestring', { value: function(locales, options) { // 1. let o be ? toobject(this value)...
... '' : nextelement.tolocalestring(locales, options); // e. let r be a string value produced by // concatenating s and r. r = s + r; // f. increase k by 1. k++; } // 10. return r. ...
... } // 10. return r. return r; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using locales and options the elements of the array are converted to strings using their tolocalestring methods. ...
...And 3 more matches
Object.prototype.toLocaleString() - JavaScript
thub.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. ...
...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. ...
...estring() 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. ...
...And 3 more matches
Object.prototype.__noSuchMethod__ - Archive of obsolete content
sn't exist on an object results in a typeerror being thrown. this behavior can be circumvented by defining a function at that object's __nosuchmethod__ member. the function takes two arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method call. the second argument is an actual array (that is, it inherits through the array.prototype chain) and not the array-like arguments object. if this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the javascript engine will revert to throwing typeerrors. examples simple test of __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); ...
...a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below. // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class. inherits from namedthing and agedthing // as well as defining address function person(name, ...
...e; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class. ...
...And 2 more matches
Array.prototype.reduce() - JavaScript
third call 11 2 2 [0, 1, 2, 3, 4] 13 fourth call 13 3 3 [0, 1, 2, 3, 4] 16 fifth call 16 4 4 [0, 1, 2, 3, 4] 20 the value returned by reduce() in this case would be 20. ...
... 2 [0, 1, 2, 3, 4] 13 fourth call 13 3 3 [0, 1, 2, 3, 4] 16 fifth call 16 4 4 [0, 1, 2, 3, 4] 20 the value returned by reduce() in this case would be 20. polyfill // production steps of ecma-262, edition 5, 15.4.4.21 // reference: http://es5.github.io/#x15.4.4.21 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce if (!array.prototype.reduce) { object.defineproperty(array.prototype, 'reduce', { value: function(callback /*, initialvalue*/) { if (this === null) { throw new typeerror( 'array.prototype.reduce ' + 'called on null or undefined' ); } if (typeof callback !== 'function') { throw new typeerror( callback + ' is not a function'); } // 1. let o be ? t...
... // « accumulator, kvalue, k, o »). if (k in o) { value = callback(value, o[k], k, o); } // d. increase k by 1. k++; } // 9. return accumulator. return value; } }); } caution: if you need to support truly obsolete javascript engines that do not support object.defineproperty(), it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable. examples sum all the values of an array let sum = [0, 1, 2, 3].reduce(function (accumulator, currentvalue) { return accumulator + currentvalue }, 0) // sum is 6 alternatively written with an arrow function: let total = [ 0, 1, 2, 3 ].reduce( ( accumulator, currentvalue ) => accumulator + currentvalue, 0 ) sum of values in an o...
...And 2 more matches
Array.prototype.reduceRight() - JavaScript
the reduceright() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. 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. see also array.prototype.reduce() for left-to-right. syntax arr.reduceright(callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters callback function to execute on each value in the array, taking four arguments: accumulator the value previously returned in the last invocation of the callback, or initialvalue, if supplied. (see below.) currentvalue the current element being processed in ...
...ard in the 5th edition; as such it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of reduceright in implementations which do not natively support it. ...
...t may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of reduceright in implementations which do not natively support it. ...
...And 2 more matches
Array.prototype.filter() - JavaScript
erefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it. ...
... all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it. this algorithm is exactly equivalent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value. ...
...round this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it. this algorithm is exactly equivalent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value. ...
...And 2 more matches
Array.prototype.find() - JavaScript
t satisfies the provided testing 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. if you need the index of the found element in the array, use findindex(). if you need to find the index of a value, use array.prototype.indexof(). (it’s similar to findindex(), but checks each element for equality with the value instead of using a testing function.) if you need to find if a value exists in an array, use array.prototype.includes(). again, it checks each element for equality with the value instead of using a testing function. if you need to find if any element satisfies the provided testing function, use array.
....indexof(). (it’s similar to findindex(), but checks each element for equality with the value instead of using a testing function.) if you need to find if a value exists in an array, use array.prototype.includes(). again, it checks each element for equality with the value instead of using a testing function. if you need to find if any element satisfies the provided testing function, use array.prototype.some(). syntax arr.find(callback(element[, index[, array]])[, thisarg]) parameters callback function to execute on each value in the array, taking 3 arguments: element the current element in the array. index optional the index (position) of the current element in the array. array optional the array that find was called on. thisarg optional object to use as this inside ...
... begins. if an existing, yet-unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time find visits that element's index. elements that are deleted are still visited. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? ...
...And 2 more matches
Array.prototype.map() - JavaScript
implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, and array have their original values and that callback.call evaluates to the original value of function.prototype.call. // production steps of ecma-262, edition 5, 15.4.4.19 // reference: http://es5.github.io/#x15.4.4.19 if (!array.prototype.map) { array.prototype.map = function(callback/*, thisarg*/) { var t, a, k; if (this == null) { throw new typeerror('this is null or not defined'); } // 1. let o be the result of calling toobject passing the |this| // value as the argu...
...assigned from each element of the array as map loops through the original array. let numbers = [1, 4, 9] let doubles = numbers.map(function(num) { return num * 2 }) // doubles is now [2, 8, 18] // numbers is still [1, 4, 9] using map generically this example shows how to use map on a string to get an array of bytes in the ascii encoding representing the character values: let map = array.prototype.map let a = map.call('hello world', function(x) { return x.charcodeat(0) }) // a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] using map generically queryselectorall this example shows how to iterate through a collection of objects collected by queryselectorall. this is because queryselectorall returns a nodelist (which is a collection of objects). in this case, we return ...
..., 114, 108, 100] using map generically queryselectorall this example shows how to iterate through a collection of objects collected by queryselectorall. this is because queryselectorall returns a nodelist (which is a collection of objects). in this case, we return all the selected options' values on the screen: let elems = document.queryselectorall('select option:checked') let values = array.prototype.map.call(elems, function(obj) { return obj.value }) an easier way would be the array.from() method. tricky use case (inspired by this blog post) it is common to use the callback with one argument (the element being traversed). certain functions are also commonly used with one argument, even though they take additional optional arguments. these habits may lead to confusing behaviors. consi...
...And 2 more matches
Array.prototype.some() - JavaScript
nt in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. ...
...s, allowing use of some() in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values and that fun.call evaluates to the original value of function.prototype.call(). ...
...in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values and that fun.call evaluates to the original value of function.prototype.call(). ...
...And 2 more matches
Array.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array. syntax arr.values() return value a new array iterator object. ...
...s a new array iterator object that contains the values for each index in the array. syntax arr.values() return value a new array iterator object. examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. ...
...contains the values for each index in the array. syntax arr.values() return value a new array iterator object. examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. ...
...And 2 more matches
Object.prototype.hasOwnProperty() - JavaScript
roperty to test. return value a boolean indicating whether or not the object has the specified property as own property. description all descendents of object inherit the hasownproperty method. this method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. if an object is an array, hasownproperty method can check whether an index exists. note hasownproperty returns true even if the value of the property is null or undefined. o = new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true examples using hasownproperty to test for a property's existe...
... hasownproperty to test for a property's existence the following example determines whether the o object contains a property named 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 lo...
... ...
...And 2 more matches
Object.prototype.propertyIsEnumerable() - JavaScript
op) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property, this method returns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.propertyisenumerable(0); // returns true user...
...ble(0); // returns true a.propertyisenumerable('length'); // returns false math.propertyisenumerable('random'); // returns false this.propertyisenumerable('math'); // returns false direct vs. ...
...propertyisenumerable('math'); // returns false direct vs. ...
...And 2 more matches
String.prototype.trimStart() - JavaScript
quest. syntax str.trimstart(); str.trimleft(); return value a new string representing the calling string stripped of whitespace from its beginning (left end). description the trimstart() / trimleft() methods return the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. ...
...the trimstart() / trimleft() methods return the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, for web compatibility reasons, trimleft remains as an alias to trimstart. ...
... aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, for web compatibility reasons, trimleft remains as an alias to trimstart. ...
...And 2 more matches
TypedArray.prototype.findIndex() - JavaScript
st invocation of callback. elements that are appended to the typed array after the call to findindex begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. ...
...lements that are appended to the typed array after the call to findindex begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. ...
... the typed array after the call to findindex begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. ...
...And 2 more matches
JS_GetPrototype
retrieves an object's prototype. syntax bool js_getprototype(jscontext *cx, js::handleobject obj, js::mutablehandleobject protop); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object for which to retrieve the prototype. protop js::mutablehandleobject out parameter. if successful, receives prototype object of obj. description js_getprototype retrieves the prototype of a specified object, obj. a prototype object provides properties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. ...
...ct object for which to retrieve the prototype. protop js::mutablehandleobject out parameter. if successful, receives prototype object of obj. description js_getprototype retrieves the prototype of a specified object, obj. a prototype object provides properties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. if js_getprototype returns false, that signals an exception, which should be handled as usual. otherwise, it stores a pointer to the prototype or null to *protop and returns true. to set an object's prototype, use js_setprototype. ...
...object provides properties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. if js_getprototype returns false, that signals an exception, which should be handled as usual. otherwise, it stores a pointer to the prototype or null to *protop and returns true. ...
...roperties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. if js_getprototype returns false, that signals an exception, which should be handled as usual. otherwise, it stores a pointer to the prototype or null to *protop and returns true. to set an object's prototype, use js_setprototype. ...
Object.prototype.valueOf() - JavaScript
expected. by default, the valueof method is inherited by every object descended from object. every built-in core object overrides this method to return an appropriate value. if an object has no primitive value, valueof returns the object itself. you can use valueof within your own code to convert a built-in object into a primitive value. when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and you want to create a valueof method for it. the following code assigns a user-defined function to the object's valueof m...
...custom method instead of the default object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and you want to create a valueof method for it. the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with 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.va...
...alueof() 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. ...
... ...
Reflect.setPrototypeOf() - JavaScript
the static reflect.setprototypeof() method is the same method as object.setprototypeof(), except for its return type. it sets the prototype (i.e., the internal [[prototype]] property) of a specified object to another object or to null, and returns true if the operation was successful, or false otherwise. 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 reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. prototype the object's new prototype (an object or null). return value a boolean indicating whether or not the prototype was successfully set. ex...
...ps://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. prototype the object's new prototype (an object or null). return value a boolean indicating whether or not the prototype was successfully set. exceptions a typeerror, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. ...
...w prototype (an object or null). return value a boolean indicating whether or not the prototype was successfully set. exceptions a typeerror, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.setprototypeof({}, null) // true // returns false if target is not extensible. reflect.setprototypeof(object.freeze({}), null) // false // returns false if it cause a prototype chain cycle. ...
...ing reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.setprototypeof({}, null) // true // returns false if target is not extensible. reflect.setprototypeof(object.freeze({}), null) // false // returns false if it cause a prototype chain cycle. let target = {} let proto = object.create(target) reflect.setprototypeof(target, proto) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.setprototypeof' in that specification. ...
RegExp.prototype[@@replace]() - JavaScript
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.replace](str, newsubstr|function) parameters str a string that is a target of the replacement. newsubstr (replacement) the string that replaces the substring. ...
...substr (replacement) the string that replaces the substring. a number of special replacement patterns are supported; see the specifying a string as a parameter section in string.prototype.replace() page. function (replacement) a function to be invoked to create the new substring. the arguments supplied to this function are described in the specifying a function as a parameter section in string.prototype.replace() page. return value a new string with some or all matches of a pattern replaced by a replacement. description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object. for example, following two examples return same result. 'abc'.replace(/a/, 'a'); /a/[symbol.replace]('abc', 'a'); this method exists for customizing replace behavio...
...a pattern replaced by a replacement. description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object. for example, following two examples return same result. 'abc'.replace(/a/, 'a'); /a/[symbol.replace]('abc', 'a'); this method exists for customizing replace behavior in regexp subclass. if pattern argument is not a regexp object, string.prototype.replace() doesn't call this method, nor creates a regexp object. examples direct call this method can be used in almost the same way as string.prototype.replace(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-01'; var newstr = re[symbol.replace](str, '.'); console.log(newstr); // 2016.01.01 using @@replace in subclasses subclasses of regex...
... in subclasses subclasses of regexp can override the [@@replace]() method to modify the default behavior. class myregexp extends regexp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [symbol.replace](str, replacement) { // perform @@replace |count| times. var result = str; for (var i = 0; i < this.count; i++) { result = regexp.prototype[symbol.replace].call(this, result, replacement); } return result; } } var re = new myregexp('\\d', '', 3); var str = '01234567'; var newstr = str.replace(re, '#'); // string.prototype.replace calls re[@@replace]. console.log(newstr); // ###34567 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@replace]' in that specification. ...
RegExp.prototype[@@split]() - JavaScript
optional integer specifying a limit on the number of splits to be found. the [@@split]() method still splits on every match of this regexp pattern (or, in the syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern. return value an array containing substrings as its elements. ...
... let re = /-/g; let str = '2016-01-02'; let result = re[symbol.split](str); console.log(result); // ["2016", "01", "02"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior. ...
...it(), except the different this and the different order of arguments. let re = /-/g; let str = '2016-01-02'; let result = re[symbol.split](str); console.log(result); // ["2016", "01", "02"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior. ...
...2"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior. class myregexp extends regexp { [symbol.split](str, limit) { let result = regexp.prototype[symbol.split].call(this, str, limit); return result.map(x => "(" + x + ")"); } } let re = new myregexp('-'); let str = '2016-01-02'; let result = str.split(re); // string.prototype.split calls re[@@split]. console.log(result); // ["(2016)", "(01)", "(02)"] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@split]' in that specification. ...
String.prototype.endsWith() - JavaScript
gth. return value true if the given characters are found at the end of the string; otherwise, false. description this method lets you determine whether or not a string ends with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. ...
... the end of the string; otherwise, false. description this method lets you determine whether or not a string ends with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. ...
...ise, false. description this method lets you determine whether or not a string ends with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. ...
... ...
JS_GetErrorPrototype
this article covers features introduced in spidermonkey 38 return the original value of error.prototype. syntax jsobject * js_geterrorprototype(jscontext *cx); name type description cx jscontext * pointer to a js context whose errors should be reported via your function. other contexts in the same runtime can have their own error reporting functions. ...
...atures introduced in spidermonkey 38 return the original value of error.prototype. syntax jsobject * js_geterrorprototype(jscontext *cx); name type description cx jscontext * pointer to a js context whose errors should be reported via your function. other contexts in the same runtime can have their own error reporting functions. description js_geterrorprototype returns the original value of error.prototype from the global object of the current compartment of cx. ...
...name type description cx jscontext * pointer to a js context whose errors should be reported via your function. ...
Array.prototype[@@unscopables] - JavaScript
ecmascript standard prior to the es2015 version. these properties are excluded from with statement bindings. description the default array properties that are excluded from with bindings are: copywithin() entries() fill() find() findindex() includes() keys() values() see symbol.unscopables for how to set unscopables for your own objects. property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the v...
... enumerable no configurable yes examples use in with environments the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the with statement. ...
..., in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] specifications specification ecmascript (ecma-262)the definition of 'array.prototype[@@unscopables]' in that specification. ...
Array.prototype.every() - JavaScript
er implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values, and that callbackfn.call evaluates to the original value of function.prototype.call. if (!array.prototype.every) { array.prototype.every = function(callbackfn, thisarg) { 'use strict'; var t, k; if (this == null) { throw new typeerror('this is null or not defined'); } // 1. let o be the result of calling toobject passing the this // value as the argument. var o = object(this); // 2. let lenvalue be the result of calling the get...
... toobject 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...
... ...
Array.prototype.fill() - JavaScript
tive, it is treated as array.length + start. if end is negative, it is treated as array.length + end. fill is intentionally generic: it does not require that its this value be an array object. fill is a mutator method: it will change the array itself and return it, not a copy of it. if the first parameter is an object, each slot in the array will reference that object. polyfill if (!array.prototype.fill) { object.defineproperty(array.prototype, 'fill', { value: function(value) { // steps 1-2. if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-7. var start = arguments[1]; var relativestart = start >> 0; // step 8. ...
...ep 11. var finalvalue = relativeend < 0 ? math.max(len + relativeend, 0) : math.min(relativeend, len); // step 12. while (k < finalvalue) { o[k] = value; k++; } // step 13. return o; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3] [1, 2, 3].fill(4, -3, -2) // [4, 2, 3] [1, 2, 3].fill(4, nan, nan) // [1, 2, 3...
... ...
Array.prototype.findIndex() - JavaScript
invocation of callback. callback will not process the elements appended to the array after the call to findindex() begins. if an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findindex() visits the element's index. elements that are deleted are still visited. polyfill // https://tc39.github.io/ecma262/#sec-array.prototype.findindex if (!array.prototype.findindex) { object.defineproperty(array.prototype, 'findindex', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; //...
... 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; }, configurable: true, writable: true }); } if you need to support truly obsolete javascript engines that do not support object.defineproperty, it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable. examples find the index of a prime number in an array the following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number. function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, ...
... ...
Array.prototype.lastIndexOf() - JavaScript
de at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, number, math.floor, math.abs, and math.min have their original values. ...
...ts, allowing use of lastindexof in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, number, math.floor, math.abs, and math.min have their original values. ...
... ...
Array.prototype.push() - JavaScript
d array. do not use this method if the second array (morevegs in the example) is very large because the maximum number of parameters that one function can take is limited in practice. see apply() for more details. let vegetables = ['parsnip', 'potato'] let morevegs = ['celery', 'beetroot'] // merge the second array into the first one // equivalent to vegetables.push('celery', 'beetroot') array.prototype.push.apply(vegetables, morevegs) console.log(vegetables) // ['parsnip', 'potato', 'celery', 'beetroot'] using an object in an array-like fashion as mentioned above, push is intentionally generic, and we can use that to our advantage. array.prototype.push can work on an object just fine, as this example shows. note that we don't create an array to store a collection of objects. instead, we s...
...['parsnip', 'potato', 'celery', 'beetroot'] using an object in an array-like fashion as mentioned above, push is intentionally generic, and we can use that to our advantage. array.prototype.push can work on an object just fine, as this example shows. note that we don't create an array to store a collection of objects. instead, we store the collection on the object itself and use call on array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way javascript allows us to establish the execution context in any way we want. let obj = { length: 0, addelem: function addelem(elem) { // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem) } } // let's add ...
... ...
Array.prototype.slice() - JavaScript
e: 2.2}}, 2] mycar[0].color = red newcar[0].color = red the new color of my honda is purple mycar[0].color = purple newcar[0].color = purple array-like objects slice method can also be called to convert array-like objects/collections to a new array. you just bind the method to the object. the arguments inside a function is an example of an 'array-like object'. ...
... = purple array-like objects slice method can also be called to convert array-like objects/collections to a new array. you just bind the method to the object. the arguments inside a function is an example of an 'array-like object'. function list() { return array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] binding can be done with the call() method of function.prototype and it can also be reduced using [].slice.call(arguments) instead of array.prototype.slice.call. ...
... inside a function is an example of an 'array-like object'. function list() { return array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] binding can be done with the call() method of function.prototype and it can also be reduced using [].slice.call(arguments) instead of array.prototype.slice.call. anyway, it can be simplified using bind. let unboundslice = array.prototype.slice let slice = function.prototype.call.bind(unboundslice) function list() { return slice(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.slice' in that specification. ...
Date.prototype.toISOString() - JavaScript
ub.com/mdn/interactive-examples and send us a pull request. syntax dateobj.toisostring() return value a string representing the given date in the iso 8601 format according to universal time. polyfill this method was standardized in ecma-262 5th edition. ...
...cording to universal time. polyfill this method was standardized in ecma-262 5th edition. ...
... ...
Date.prototype.toString() - JavaScript
ecified 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 hour: 2 digit hour of day, e.g. ...
... left bracket, i.e. "(" an implementation dependent string representation of the timezone, which might be an abbreviation or full name (there is no standard for names or abbreviations of timezones), e.g. "line islands time" or "lint" right bracket, i.e. ")" e.g. "sat sep 01 2018 14:53:26 gmt+1400 (lint)" until ecmascript 2018 (edition 9), the format of the string returned by date.prototype.tostring was implementation dependent. therefore it should not be relied upon to be in the specified format. the tostring() method is automatically called when a date is to be represented as a text value, e.g. console.log(new date()), or when a date is used in a string concatenation, such as var today = 'today is ' + new date(). tostring() is a generic method, it does not require that its this ...
...nstance, a typeerror is thrown. examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification. ...
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. ...
... ...
Intl.Collator.prototype.compare() - JavaScript
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 collator.compare(string1, string2) parameters string1 string2 the strings to compare against each other. description the compare getter function returns a number indicating how string1 and string2 compare to each other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. ...
...ch other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. examples using compare for array sort use the compare getter function for sorting arrays. note that the function is bound to the collator from which it was obtained, so it can be passed directly to array.prototype.sort(). var a = ['offenbach', 'Österreich', 'odenwald']; var collator = new intl.collator('de-u-co-phonebk'); a.sort(collator.compare); console.log(a.join(', ')); // → "odenwald, Österreich, offenbach" using compare for array search use the compare getter function for finding matching strings in arrays: var a = ['congrès', 'congres', 'assemblée', 'poisson']; var collator = new intl.col...
... ...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
syntax datetimeformat.formattoparts(date) parameters date optional the date to format. return value an array of objects containing the formatted date in parts. description the formattoparts() method is useful for custom formatting of date strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
..., { type: 'minute', value: '00' }, { type: 'literal', value: ':' }, { type: 'second', value: '42' }, { type: 'fractionalsecond', value: '000' }, { type: 'literal', value: ' ' }, { type: 'dayperiod', value: 'am' } ] now the information is available separately and it can be formatted and concatenated again in a customized way. for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce(). var datestring = formatter.formattoparts(date).map(({type, value}) => { switch (type) { case 'dayperiod': return `<b>${value}</b>`; default : return value; } }).reduce((string, part) => string + part); this will make the day period bold, when using the formattoparts() method. console.log(f...
... ...
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
each element of the resulting array has two properties: type and value. ...
... each element of the resulting array has two properties: type and value. ...
... returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. syntax intl.listformat.prototype.formattoparts(list) parameters list an array of values to be formatted according to a locale. return value an array of components which contains the formatted parts from the list. description whereas intl.listformat.prototype.format() returns a string being the formated version of the list (according to the given locale and style options), formattoparts() returns an array of the different components of the formated string. each element of the resulting array has two properties: type and value. the type property may be either "element", which refers to a value from the list, or "literal" which refers to a linguistic c...
Intl.NumberFormat.prototype.format() - JavaScript
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 numberformat.format(number) parameters number a number or bigint to format. description the format getter function formats a number into a string according to the locale and formatting options of this numberformat object. ...
...r options = { style: 'currency', currency: 'rub' }; var numberformat = new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array. note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map. this is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs. var a = [123456.789, 987654.321, 456789.123]; var numberformat = new intl.numberformat('es-es'); var formatted = a.map(n => numberformat.format(n)); console.log(formatted.join('; ')); // → "123.456,789; 987.654...
...tibility with existing programs. var a = [123456.789, 987654.321, 456789.123]; var numberformat = new intl.numberformat('es-es'); var formatted = a.map(n => numberformat.format(n)); console.log(formatted.join('; ')); // → "123.456,789; 987.654,321; 456.789,123" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.format' in that specification. ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
return value an array of objects containing the formatted number in parts. description the formattoparts() method is useful for custom formatting of number strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
..."integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" }, { type: "decimal", value: "," }, { type: "fraction", value: "00" }, { type: "literal", value: " " }, { type: "currency", value: "€" } ] now the information is available separately and it can be formatted and concatenated again in a customized way. for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce(). var numberstring = formatter.formattoparts(number).map(({type, value}) => { switch (type) { case 'currency': return `<strong>${value}</strong>`; default : return value; } }).reduce((string, part) => string + part); this will make the currency bold, when using the formattoparts() method. co...
... ...
Number.prototype.toLocaleString() - JavaScript
); } catch (e) { return e.name === 'rangeerror'; } return false; } prior to es5.1, implementations were not required to throw a range error exception if tolocalestring is called with arguments. a check that works in all hosts, including those supporting ecma-262 prior to ed 5.1, is to test for the features specified in ecma-402 that are required to support regional options for number.prototype.tolocalestring directly: function tolocalestringsupportsoptions() { return !!(typeof intl == 'object' && intl && typeof intl.numberformat == 'function'); } this tests for a global intl object, checks that it's not null and that it has a numberformat property that is a function. using locales this example shows some of the variations in localized number formats. in order to get the format o...
... ...
... ...
Promise.prototype.then() - JavaScript
the execution of a function to the moment the stack is empty settimeout(() => { console.log(thenprom); }); // logs, in order: // promise {[[promisestatus]]: "pending", [[promisevalue]]: undefined} // "this gets called after the end of the main stack. the value received and returned is: 33" // promise {[[promisestatus]]: "resolved", [[promisevalue]]: 33} description as the then and promise.prototype.catch() methods return promises, they can be chained — an operation called composition. examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which al...
... const nexttick = (() => { const noop = () => {}; // literally const nexttickpromise = () => promise.resolve().then(noop); const rfab = reflect.apply.bind; // (thisarg, fn, thisarg, [...args]) const nexttick = (fn, ...args) => ( fn !== undefined ? promise.resolve(args).
... ...
RegExp.prototype[@@match]() - JavaScript
tive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.match](str) parameters str a string that is a target of the match. return value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. description this method is called internally in string.prototype.match(). for example, the following two examples return same result. 'abc'.match(/a/); /a/[symbol.match]('abc'); this method exists for customizing match behavior within regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; ...
...e.match(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str); console.log(result); // ["2016", "01", "02"] using @@match in subclasses subclasses of regexp can override the [@@match]() method to modify the default behavior. class myregexp extends regexp { [symbol.match](str) { let result = regexp.prototype[symbol.match].call(this, str); if (!result) return null; return { group(n) { return result[n]; } }; } } let re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // string.prototype.match calls re[@@match]. console.log(result.group(1)); // 2016 console.log(result.group(2)); // 01 console.log(result.group(3)); // 02 ...
...eturn result[n]; } }; } } let re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // string.prototype.match calls re[@@match]. console.log(result.group(1)); // 2016 console.log(result.group(2)); // 01 console.log(result.group(3)); // 02 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@match]' in that specification. ...
RegExp.prototype[@@matchAll]() - JavaScript
ce 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 regexp[symbol.matchall](str) parameters str a string that is a target of the match. return value an iterator. description this method is called internally in string.prototype.matchall(). for example, the following two examples return same result. 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing the behavior of matchall() in regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments. let re = ...
...et str = '2016-01-02'; let result = re[symbol.matchall](str); console.log(array.from(result, x => x[0])); // ["2016", "01", "02"] using @@matchall in subclasses subclasses of regexp can override the [@@matchall]() method to modify the default behavior. ...
... ...
RegExp.prototype.flags - JavaScript
the flags property returns a string consisting of the flags of the current regular expression 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. ...
... please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of regexp.prototype.flags writable no enumerable no configurable yes description flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). ...
...nd us a pull request. property attributes of regexp.prototype.flags 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. ...
String.prototype.codePointAt() - JavaScript
returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. polyfill the following extends strings to include the codepointat() function as specified in ecmascript 2015 for browsers without native support. ...
... is a next code unit ) { second = string.charcodeat(index + 1); if (second >= 0xdc00 && second <= 0xdfff) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined looping with codepointat() for (let codepoint of ...
... ...
String.prototype.includes() - JavaScript
not a string includes another string. case-sensitivity the includes() method is case sensitive. for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
...tring. case-sensitivity the includes() method is case sensitive. for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
... ...
String.prototype.match() - JavaScript
lar expression does not include the g flag, str.match() will return the same result as regexp.exec(). other methods if you need to know if a string matches a regular expression regexp, use regexp.test(). if you only want the first match found, you might want to use regexp.exec() instead. if you want to obtain capture groups and the global flag is set, you need to use regexp.exec() or string.prototype.matchall() instead. examples using match() in the following example, match() is used to find 'chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. the regular expression includes the i flag so that upper/lower case differences will be ignored. const str = 'for more information, see chapter 3.4.5.1'; const re = /see (chapter \d+...
...nstrates the use of the global and ignore case flags with match(). all letters a through e and a through e are returned, each its own element in the array. const str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; const regexp = /[a-e]/gi; const matches_array = str.match(regexp); console.log(matches_array); // ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] note: see also string.prototype.matchall() and advanced searching with flags. using named capturing groups in browsers which support named capturing groups, the following code captures "fox" or "cat" into a group named "animal": const paragraph = 'the quick brown fox jumps over the lazy dog. it barked.'; const capturingregex = /(?<animal>fox|cat) jumps over/; const found = paragraph.match(capturingregex); console.log(found...
...nfinity is the number. returns ["infinity"] str1.match(+infinity); // returns ["infinity"] str1.match(-infinity); // returns ["-infinity"] str2.match(65); // returns ["65"] str2.match(+65); // a number with a positive sign. returns ["65"] str3.match(null); // returns ["null"] specifications specification ecmascript (ecma-262)the definition of 'string.prototype.match' in that specification. ...
String.prototype.repeat() - JavaScript
new string containing the specified number of copies of the given string. exceptions rangeerror: repeat count must be non-negative. rangeerror: repeat count must be less than infinity and not overflow maximum string size. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.repeat() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new typeerror('can\'t convert ' + this + ' to object'); var str = '' + this; // to convert string to integer. count = +count; // check nan if (count != count) count = 0; if (count < 0) throw ne...
... ...
... ...
String.prototype.startsWith() - JavaScript
urn value true if the given characters are found at the beginning of the string; otherwise, false. description this method lets you determine whether or not a string begins with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
...ng of the string; otherwise, false. description this method lets you determine whether or not a string begins with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.startswith() with the following snippet: if (!string.prototype.startswith) { object.defineproperty(string.prototype, 'startswith', { value: function(search, rawpos) { var pos = rawpos > 0 ? rawpos|0 : 0; return this.substring(pos, pos + search.length) === search; } }); } a more robust (fully es2015 specification compliant), but less performant and compact, polyfill is available on github by mathias bynens. ...
...able on github by mathias bynens. examples using startswith() //startswith let str = 'to be, or not to be, that is the question.' console.log(str.startswith('to be')) // true console.log(str.startswith('not to be')) // false console.log(str.startswith('not to be', 10)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.startswith' in that specification. ...
String.prototype.substr() - JavaScript
s not support negative values for the start index. ...
...{string} */ string.prototype.substr = function(substr) { return function(start, length) { // call the original method return substr.call(this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start < 0 ? ...
... ...
String.prototype.trimEnd() - JavaScript
s a pull request. syntax str.trimend(); str.trimright(); return value a new string representing the calling string stripped of whitespace from its (right) end. description the trimend() / trimright() methods return the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. ...
...tion the trimend() / trimright() methods return the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility reasons, trimright remains as an alias to trimend. ...
... ...
TypedArray.prototype.copyWithin() - JavaScript
typedarray is one of the typed array types here. the source for this interactive example is stored in a github repository. ...
...s and send us a pull request. syntax typedarray.copywithin(target, start[, end = this.length]) parameters target target start index position where to copy the elements to. start source start index position where to start copying elements from. end optional optional. source end index position where to end copying elements from. return value the modified array. description see array.prototype.copywithin for more details. examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.
....copywithin for more details. examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.copywithin' in that specification. ...
TypedArray.prototype.join() - JavaScript
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.join([separator = ',']); parameters separator optional. specifies a string to separate each element. the separator is converted to a string if necessary. if omitted, the typed array elements are separated with a comma (","). ...
... specifies a string to separate each element. the separator is converted to a string if necessary. if omitted, the typed array elements are separated with a comma (","). return value a string with all array elements joined. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!uint8array.prototype.join) { object.defineproperty(uint8array.prototype, 'join', { value: array.prototype.join }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using join var uint8 = new uint8array([1,2,3]); uint8...
...ngines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using join var uint8 = new uint8array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.join' in that specification. ...
TypedArray.prototype.reduce() - JavaScript
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. ...
...value will be equal to the second. if the typed array is empty and no initialvalue was provided, typeerror would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. ...
...lue was provided, typeerror would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. polyfill this method uses the same algorithm as array.prototype.reduce(), so the same polyfill can be used here: simply replace array.prototype.reduce with typedarray.prototype.reduce. examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduce(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduce' in that specification. ...
TypedArray.prototype.slice() - JavaScript
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.slice([begin[, end]]) parameters begin optional zero-based index at which to begin extraction. a negative index can be used, indicating an offset from the end of the sequence. ...
...alue a new typed array containing the extracted elements. description the slice method does not alter. it returns a shallow copy of elements from the original typed array. if a new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. if (!uint8array.prototype.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { return new uint8array(array.prototype.slice.call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. e...
...l, as you can't make them non-enumerable. examples return a portion of an existing typed array const uint8 = new uint8array([1,2,3]); uint8.slice(1); // uint8array [ 2, 3 ] uint8.slice(2); // uint8array [ 3 ] uint8.slice(-2); // uint8array [ 2, 3 ] uint8.slice(0,1); // uint8array [ 1 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.slice' in that specification. ...
TypedArray.prototype.some() - JavaScript
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. ...
...d for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some does not mutate the typed array on which it is called. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!uint8array.prototype.some) { object.defineproperty(uint8array.prototype, 'some', { value: array.prototype.some }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples testing size of all typed array elements the followin...
... ...
TypedArray.prototype.toLocaleString() - JavaScript
typedarray is one of the typed array types here. ...
...typedarray is one of the typed array types here. ...
... ...
WebAssembly.Table.prototype.set() - JavaScript
if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. ...
...ence stored at a given index to a different value. syntax table.set(index, value); parameters index the index of the function reference you want to mutate. value the value you want to mutate the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void. ...
...l to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently return null). var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
the non-standard tolocaleformat() method converts a date to a string using the specified formatting. intl.datetimeformat is an alternative to format dates in a standards-compliant way. see also the newer version of date.prototype.tolocaledatestring(). this feature has been removed and will no longer work in firefox 58+. see warning: date.prototype.tolocaleformat is deprecated for more information and migration help. syntax dateobj.tolocaleformat(formatstring) parameters formatstring a format string in the same format expected by the strftime() function in c. return value a string representing the given date using the specified formatting. description the tolocaleformat() method provides greater software control over the formatting of the generated date and/or time. names for...
...g this method. examples using tolocaleformat() var today = new date(); var date = today.tolocaleformat('%a, %b %e, %y'); in this example, tolocaleformat() returns a string such as "wednesday, october 3, 2007". note that the format string in this example is not properly localized, which will result in the problems described above. polyfill when using the datejs library you can polyfill date.prototype.tolocaledatestring() like this: if (!date.prototype.tolocaleformat) { (function() { date.prototype.tolocaleformat = function(formatstring) { return this.format(formatstring); }; }()); } specifications not part of any standard. ...
Prototype-based programming - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first defining its class. ...
... prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first defining its class. ...
Prototype - MDN Web Docs Glossary: Definitions of Web-related terms
a prototype is a model that displays the appearance and behavior of an application or product early in the development lifecycle. ...
... a prototype is a model that displays the appearance and behavior of an application or product early in the development lifecycle. ...
JS_GetArrayPrototype
this article covers features introduced in spidermonkey 24 retrieves the original, canonical array.prototype for an object's global object. syntax jsobject * js_getarrayprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose array.prototype is being retrieved. description js_getarrayprototype() retrieves the original array.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global array property...
...ect from the global whose array.prototype is being retrieved. description js_getarrayprototype() retrieves the original array.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global array property is modified, but this method returns only the original value. ...
JS_GetClassPrototype
get the builtin class prototype object. syntax bool js_getclassprototype(jscontext *cx, jsprotokey key, js::mutablehandle<jsobject*> objp); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. key jsprotokey the key of the prototype. objp js::mutablehandle&lt;jsobject*&gt; out parameter. if successful, receive the class prototype object. description js_getclassprototype gets the builtin class costructor for the specified prototype key. if successful, js_getclassprototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is undefined. see also mxr id sear...
...ndle&lt;jsobject*&gt; out parameter. if successful, receive the class prototype object. description js_getclassprototype gets the builtin class costructor for the specified prototype key. if successful, js_getclassprototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is undefined. ...
JS_GetFunctionPrototype
this article covers features introduced in spidermonkey 17 retrieves the original, canonical function.prototype for an object's global object. syntax jsobject * js_getfunctionprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose function.prototype is being retrieved. description js_getfunctionprototype() retrieves the original function.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if...
...bal whose function.prototype is being retrieved. description js_getfunctionprototype() retrieves the original function.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global function property is modified, but this method returns only the original value. ...
JS_GetObjectPrototype
this article covers features introduced in spidermonkey 17 retrieves the original, canonical object.prototype for an object's global object. syntax jsobject * js_getobjectprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose object.prototype is being retrieved. description js_getobjectprototype() retrieves the original object.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global object pr...
...rom the global whose object.prototype is being retrieved. description js_getobjectprototype() retrieves the original object.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global object property is modified, but this method returns only the original value. ...
NodeList.prototype.forEach() - Web APIs
Web › API › NodeList › forEach
unction(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); the above code results in the following: [object htmlparagraphelement], 0, mythisarg [object text], 1, mythisarg [object htmlspanelement], 2, mythisarg polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { callback.call(thisarg, this[i], i, this); } }; } or if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = array.prototype.foreach; } the above behavior is how many browsers actuall...
... specifications specification status comment web idlthe definition of 'foreach' in that specification. candidate recommendation defines foreach on iterable declarations browser compatibility the compatibility table on this page is generated from structured data. ...
TextEncoder.prototype.encode() - Web APIs
syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. ...
... living standard initial definition. ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
the javascript warning "date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead" occurs when the non-standard date.prototype.tolocaleformat method is used. message warning: date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead error type warning. javascript execution won't be halted. what went wrong? the non-standard date.prototype.tolocaleformat method is deprecated and shouldn't be used anymore. it uses a format string in the same format expected by the strftime() function in c. the function is no longer available in firefox 58+. examples deprecated syntax the date.prototype.tolocaleformat method is deprecated and will be removed (no cross-browser support, available in firefox only). var today = new date(); var date = t...
...= today.tolocaleformat('%a, %e. %b %y'); console.log(date); // in german locale // "freitag, 10. märz 2017" alternative standard syntax using the ecmascript intl api the ecma-402 (ecmascript intl api) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in chrome 24+, firefox 29+, ie11+, safari10+). you can now either use the date.prototype.tolocaledatestring method if you just want to format one date. var today = new date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.tolocaledatestring('de-de', options); console.log(date); // "freitag, 10. märz 2017" or, you can make use of the intl.datetimeformat object, which allows you to cache an object with most of t...
Array.prototype[@@iterator]() - JavaScript
+ "</li>"; } result alternative iteration var arr = ['a', 'b', 'c', 'd', 'e']; var earr = arr[symbol.iterator](); console.log(earr.next().value); // a console.log(earr.next().value); // b console.log(earr.next().value); // c console.log(earr.next().value); // d console.log(earr.next().value); // e use case for brace notation the use case for this syntax over using the dot notation (array.prototype.values()) is in a case where you don't know what object is going to be ahead of time. if you have a function that takes an iterator and then iterate over the value, but don't know if that object is going to have a [iterable].prototype.values method. this could be a built-in object like string object or a custom object. function logiterable(it) { if (!(symbol.iterator in object.getprototypeof(it...
... ...
Array.prototype.copyWithin() - JavaScript
asted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap. the copywithin function is intentionally generic, it does not require that its this value be an array object. the copywithin method is a mutable method. it does not alter the length of this, but it will change its content and create new properties, if necessary. polyfill if (!array.prototype.copywithin) { object.defineproperty(array.prototype, 'copywithin', { value: function(target, start/*, end*/) { // steps 1-2. if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-8. var relativetarget = target >> 0; var to = relativetarget < 0 ? ma...
... ...
Array.prototype.flatMap() - JavaScript
tvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing callback. return value a new array with each element being the result of the callback function and flattened to a depth of 1. description see array.prototype.map() for a detailed description of the callback function. the flatmap method is identical to a map followed by a call to flat of depth 1. alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.reduce((acc, x) => acc.concat([x, x * 2]), []); // [1, 2, 2, 4, 3, 6, 4, 8] note, however, that this is inefficient and should be avoided for ...
... ...
Array.prototype.includes() - JavaScript
.includes('c', -100) // true arr.includes('a', -2) // false includes() used as a generic method includes() method is intentionally generic. it does not require this value to be an array object, so it can be applied to other kinds of objects (e.g. array-like objects). the example below illustrates includes() method called on the function's arguments object. (function() { console.log(array.prototype.includes.call(arguments, 'a')) // true console.log(array.prototype.includes.call(arguments, 'd')) // false })('a','b','c') please do not add polyfills on reference articles. for more details and discussion, see https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500 specifications specification ecmascript (ecma-262)th...
...s, 'a')) // true console.log(array.prototype.includes.call(arguments, 'd')) // false })('a','b','c') please do not add polyfills on reference articles. for more details and discussion, see https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500 specifications specification ecmascript (ecma-262)the definition of 'array.prototype.includes' in that specification. ...
Array.prototype.pop() - JavaScript
e last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. if you call pop() on an empty array, it returns undefined. array.prototype.shift() has similar behavior to pop, but applied to the first element in an array. examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element. var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); ...
...myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter. var myfish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4}; var popped = array.prototype.pop.call(myfish); //same syntax for using apply( ) console.log(myfish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} console.log(popped); // 'sturgeon' specifications specification ecmascript (ecma-262)the definition of 'array.prototype.pop' in that specification. ...
Array.prototype.shift() - JavaScript
the values at consecutive indexes down, then returns the removed value. if the length property is 0, undefined is returned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. examples removing an element from an array the following code displays the myfish array before and after removing its first element. it also displays the removed element: var myfish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myfish before:', json.stringify(myfish)); // myfish before: ['angel', 'c...
...ed in condition inside while loop. in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ecma-262)the definition of 'array.prototype.shift' in that specification. ...
BigInt.prototype.toLocaleString() - JavaScript
...
... ...
BigInt.prototype.toString() - JavaScript
tional. 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 than 9. for example, for hexadecimal numbers (base 16) a through f are ...
... ...
Boolean.prototype.toString() - JavaScript
ive 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 objects and values, the built-in tostring() method returns the string "true" or "false" depending on the value of the bo...
...atenation. 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. ...
Date.prototype.getDay() - JavaScript
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.getday() return value an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. ...
....datetimeformat with an options parameter. using this method, the internationalization is made easier: var options = { weekday: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // monday console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // montag specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getday' in that specification. ...
Date.prototype.toLocaleString() - JavaScript
...
...9-01-01t01:00:00z").tolocalestring("en-us"); // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples. specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocalestring' in that specification. ecmascript internationalization api (ecma-402)the definition of 'date.prototype.tolocalestring' in that specification. ...
Date.prototype.toLocaleTimeString() - JavaScript
...
... ...
Intl.Collator.prototype.resolvedOptions() - JavaScript
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 collator.resolvedoptions() return value a new object with properties reflecting the locale and collation options computed during the initialization of the given collator object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
... ...
Intl.DateTimeFormat.prototype.format() - JavaScript
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 datetimeformat.format(date) parameters date the date to format. description the format getter formats a date into a string according to the locale and formatting options of this intl.datetimeformat object. ...
...'long', day: 'numeric' }; var datetimeformat = new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(new date())); // → "недеља, 7. април 2013." using format with map use the format getter function for formatting all dates in an array. note that the function is bound to the intl.datetimeformat from which it was obtained, so it can be passed directly to array.prototype.map(). var a = [new date(2012, 08), new date(2012, 11), new date(2012, 03)]; var options = { year: 'numeric', month: 'long' }; var datetimeformat = new intl.datetimeformat('pt-br', options); var formatted = a.map(datetimeformat.format); console.log(formatted.join('; ')); // → "setembro de 2012; dezembro de 2012; abril de 2012" avoid comparing formatted date values to static values most of t...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
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 datetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object. ...
... ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
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 numberformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
... ...
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
syntax pluralrule.resolvedoptions() return value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
... ...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
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 relativetimeformat.formattoparts(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. ...
... value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. return value an array of objects containing the formatted relative time in parts. description the intl.relativetimeformat.prototype.formattoparts method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating it from other surrounding text. these objects have two properties: type a numberformat formattoparts type, and value, which is the string which is the component of the output. if a "part" came fr...
Number.prototype.toFixed() - JavaScript
not a number. 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': no...
...3' 2.35.tofixed(1) // returns '2.4'. note it rounds up 2.55.tofixed(1) // returns '2.5'. note it rounds down - see warning above -2.34.tofixed(1) // returns -2.3 (due to operator precedence, negative number literals don't return a string...) (-2.34).tofixed(1) // returns '-2.3' specifications specification ecmascript (ecma-262)the definition of 'number.prototype.tofixed' in that specification. ...
Number.prototype.toPrecision() - JavaScript
a string representing the number object to the specified precision. syntax numobj.toprecision([precision]) parameters precision 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. e...
... ...
Number.prototype.toString() - JavaScript
ional. 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 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 ar...
... ...
Object.prototype.__lookupGetter__() - JavaScript
operty. description if a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupgetter__ can be used to obtain a reference to the getter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof(). examples standard-compliant and non-standard ways to get a property getter var obj = { get foo() { return math.random() > 0.5 ? 'foo' : 'bar'; } }; // non-standard and deprecated way obj.__lookupgetter__('foo'); // (function() { return math.random() > 0.5 ? 'foo' : 'bar'; }) // standard-compliant way object.getownpropertydescriptor(obj, "foo").get; // (function() { return math...
... ...
Object.getPrototypeOf() - JavaScript
the object.getprototypeof() method returns the prototype (i.e. the value of the internal [[prototype]] property) of the specified 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 object.getprototypeof(obj) parameters obj the object whose prototype is to be returned. return value the prototype of the given object. if there are no inherited properties, null is returned. examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object. in...
...urn value the prototype of the given object. if there are no inherited properties, null is returned. examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object. in es2015, the parameter will be coerced to an object. object.getprototypeof('foo'); // typeerror: "foo" is not an object (es5 code) object.getprototypeof('foo'); // string.prototype (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.getprototypeof' in that specification. ...
Object.prototype.toSource() - JavaScript
ource code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code. you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
...objects to override the tosource() method. for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.name) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each core javascript type has its own tosource() method. these objects are: array.prototype.tosource() — array object. boolean.prototype.tosource() — boolean object. date.prototype.tosource() — date object. function.prototype.tosource() — function object. number.prototype.tosource() — number object. regexp.prototype.tosource() — regexp object. string.prototype.tosource() — string object. symbol.prototype.tosource() — symbol object. math.tosource() — ret...
RegExp.prototype[@@search]() - JavaScript
ase clone https://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.search](str) parameters str a string that is a target of the search. return value integer if successful, [@@search]() returns the index of the first match of the regular expression inside the string. otherwise, it returns -1. description this method is called internally in string.prototype.search(). for example, the following two examples return the same result. 'abc'.search(/a/); /a/[symbol.search]('abc'); this method exists for customizing the search behavior in regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-02...
...h](str); console.log(result); // 4 using @@search in subclasses subclass of regexp can override [@@search]() method to modify the behavior. class myregexp extends regexp { constructor(str) { super(str) this.pattern = str; } [symbol.search](str) { return str.indexof(this.pattern); } } var re = new myregexp('a+b'); var str = 'ab a+b'; var result = str.search(re); // string.prototype.search calls re[@@search]. console.log(result); // 3 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@search]' in that specification. ...
RegExp.prototype.dotAll - JavaScript
the dotall property indicates whether or not the "s" flag is used with the regular expression. dotall is a read-only property of an individual regular expression instance. property attributes of regexp.prototype.dotall writable no enumerable no configurable yes description the value of dotall is a boolean and true if the "s" flag was used; otherwise, false. the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will ma...
... ...
RegExp.prototype.global - JavaScript
the "g" flag is used with the regular expression. global is a read-only property of an individual regular expression instance. 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 regexp.prototype.global writable no enumerable no configurable yes description the value of global is a boolean and true if the "g" flag was used; otherwise, false. the "g" flag indicates that the regular expression should be tested against all possible matches in a string. a regular expression defined as both global ("g") and stic...
... ...
RegExp.prototype.ignoreCase - JavaScript
"i" flag is used with the regular expression. ignorecase is a read-only property of an individual regular expression instance. 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 regexp.prototype.ignorecase writable no enumerable no configurable yes description the value of ignorecase is a boolean and true if the "i" flag was used; otherwise, false. the "i" flag indicates that case should be ignored while attempting a match in a string. you cannot change this property directly. examples using ignorecase ...
... ...
RegExp.prototype.multiline - JavaScript
"m" flag is used with the regular expression. multiline is a read-only property of an individual regular expression instance. 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 regexp.prototype.multiline writable no enumerable no configurable yes description the value of multiline is a boolean and is true if the "m" flag was used; otherwise, false. the "m" flag indicates that a multiline input string should be treated as multiple lines. for example, if "m" is used, "^" and "$" change from matching at only...
... ...
RegExp.prototype.source - JavaScript
g containing the source text of the regexp object, and it doesn't contain the two forward slashes on both sides and any flags. 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 regexp.prototype.source writable no enumerable no configurable yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig". empty regular expressions and escaping starting with ecmascript 5, the source property no longer returns an empty string for empty regular expr...
...s an empty string for empty regular expressions. instead, the string "(?:)" is returned. in addition, line terminators (such as "\n") are escaped now. new regexp().source; // "(?:)" new regexp('\n').source === '\n'; // true, prior to es5 new regexp('\n').source === '\\n'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.source' in that specification. ...
RegExp.prototype.sticky - JavaScript
the lastindex property of this regular expression). sticky is a read-only property of an individual regular expression 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. property attributes of regexp.prototype.sticky writable no enumerable no configurable yes description the value of sticky is a boolean and true if the "y" flag was used; otherwise, false. the "y" flag indicates that it matches only from the index indicated by the lastindex property of this regular expression in the target string (and does not attempt to ...
... ...
RegExp.prototype.test() - JavaScript
/mdn/interactive-examples and send us a pull request. syntax regexobj.test(str) parameters str the string against which to match the regular expression. returns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the string.prototype.search() method (which returns the index of a match, or -1 if not found). to get more information (but with slower execution), use the exec() method. (this is similar to the string.prototype.match() method.) as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple...
...s a message which depends on the success of the test: function testinput(re, str) { let midstring; if (re.test(str)) { midstring = 'contains'; } else { midstring = 'does not contain'; } console.log(`${str} ${midstring} ${re.source}`); } using test() on a regex with the "global" flag when a regex has the global flag set, test() will advance the lastindex of the regex. (regexp.prototype.exec() also advances the lastindex property.) further calls to test(str) will resume searching str starting from lastindex. the lastindex property will continue to increase each time test() returns true. note: as long as test() returns true, lastindex will not reset—even when testing a different string! when test() returns false, the calling regex's lastindex property will reset to 0. th...
RegExp.prototype.toString() - JavaScript
teractive 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. examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' var foo = new regexp('bar', 'g'); console.log(foo.tostring()); // logs '/bar/g' empty regular expre...
... ...
RegExp.prototype.unicode - JavaScript
the "u" flag is used with a regular expression. unicode is a read-only property of an individual regular expression instance. 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 regexp.prototype.unicode writable no enumerable no configurable yes description the value of unicode is a boolean and true if the "u" flag was used; otherwise false. the "u" flag enables various unicode-related features. with the "u" flag, any unicode code point escapes will be interpreted as such, for example. you cannot change t...
...s various unicode-related features. with the "u" flag, any unicode code point escapes will be interpreted as such, for example. you cannot change this property directly. it is read-only. examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification. ...
SharedArrayBuffer.prototype.slice() - JavaScript
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 sab.slice() sab.slice(begin) sab.slice(begin, end) parameters begin optional zero-based index at which to begin extraction. ...
.... examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.slice' in that specification. ...
String.prototype.indexOf() - JavaScript
string object of the first occurrence of the specified value, starting the search at fromindex. returns -1 if the value is not found. 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. note: for the array method, see array.prototype.indexof(). syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. so, for example: 'undefined'.indexof() will return 0, as undefined is found at position 0 in the string undefined. 'undefine'.indexof() however will...
... ...
String.prototype.localeCompare() - JavaScript
...
... ...
String.prototype.matchAll() - JavaScript
str = 'abc'; str.matchall(regexp); // typeerror matchall internally makes a clone of the regexp—so, unlike regexp.exec(), lastindex does not change as the string is scanned. const regexp = regexp('[a-c]','g'); regexp.lastindex = 1; const str = 'abc'; array.from(str.matchall(regexp), m => `${regexp.lastindex} ${m[0]}`); // array [ "1 b", "1 c" ] better access to capturing groups (than string.prototype.match()) another compelling reason for matchall is the improved access to capture groups. capture groups are ignored when using match() with the global /g flag: let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; str.match(regexp); // array ['test1', 'test2'] using matchall, you can access capture groups easily: let array = [...str.matchall(regexp)]; array[0]; // ['test1', 'e', 'st1', '...
... ...
String.prototype.search() - JavaScript
ssed, it is implicitly converted to a regexp with new regexp(regexp). return value the index of the first match between the regular expression and the given string, or -1 if no match was found. description when you want to know whether a pattern is found, and also know its index within a string, use search(). (if you only want to know if it exists, use the similar test() method on the regexp prototype, which returns a boolean.) for more information (but slower execution) use match() (similar to the regular expression exec() method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g console.log(str.search(re))...
...ow a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g console.log(str.search(re)) // returns 4, which is the index of the first capital letter "j" console.log(str.search(redot)) // returns -1 cannot find '.' dot punctuation specifications specification ecmascript (ecma-262)the definition of 'string.prototype.search' in that specification. ...
String.prototype.toLocaleLowerCase() - JavaScript
...
... ...
String.prototype.toLocaleUpperCase() - JavaScript
...
... ...
String.prototype.toUpperCase() - JavaScript
his 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 str.touppercase() return value a new string representing the calling string converted to upper case. exceptions typeerror when called on null or undefined, for example, string.prototype.touppercase.call(undefined). description the touppercase() method returns the value of the string converted to uppercase. 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 t...
...ue of the string converted to uppercase. 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.trim() - JavaScript
d send us a pull request. syntax str.trim() return value a new string representing the str stripped of whitespace from both ends. description the trim() method returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whitespace from just one side. var orig = 'foo '; console.log(orig.trim()); // 'foo' s...
... ...
Symbol.prototype.description - JavaScript
of symbol objects. 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. 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. examples using description symbol('desc').tostring(); // "symbol(desc)" symbol('desc').description; // "desc" symbol('').description; // "" symbol().description; // undefined // well-known symbols sym...
... ...
Symbol.prototype.toString() - JavaScript
e 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. 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.iterat...
... ...
TypedArray.prototype.every() - JavaScript
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. ...
... ...
TypedArray.prototype.filter() - JavaScript
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.filter(callback[, thisarg]) parameters callback function to test each element of the typed array. invoked with arguments (element, index, typedarray). ...
... ...
TypedArray.prototype.forEach() - JavaScript
typedarray is one of the typed array types here. syntax typedarray.foreach(callback[, thisarg]) parameters callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the array. array the array foreach() was called upon. thisarg optional. value to use as this when executing callback. return value undefined. ...
... ...
TypedArray.prototype.includes() - JavaScript
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.includes(searchelement[, fromindex]); parameters searchelement the element to search for. fromindex optional. ...
... ...
TypedArray.prototype.indexOf() - JavaScript
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.indexof(searchelement[, fromindex = 0]) parameters searchelement element to locate in the typed array. ...
... ...
TypedArray.prototype.lastIndexOf() - JavaScript
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. ...
...e ===, or triple-equals, operator). examples using lastindexof var uint8 = new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.lastindexof(7); // -1 uint8.lastindexof(2, 3); // 3 uint8.lastindexof(2, 2); // 0 uint8.lastindexof(2, -2); // 0 uint8.lastindexof(2, -1); // 3 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.lastindexof' in that specification. ...
TypedArray.prototype.map() - JavaScript
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. ...
... ...
TypedArray.prototype.reduceRight() - JavaScript
typedarray is one of the typed array types here. syntax typedarray.reduceright(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the callback, or initialvalue, if supplied (see below). ...
... ...
TypedArray.prototype.reverse() - JavaScript
the reverse() method reverses a typed array in place. the first typed array element becomes the last and the last becomes the first. this method has the same algorithm as array.prototype.reverse(). 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.reverse(); return value the reversed array. ...
... ...
TypedArray.prototype.sort() - JavaScript
the sort() method sorts the elements of a typed array numerically in place and returns the typed array. this method has the same algorithm as array.prototype.sort(), except that sorts the values numerically instead of as strings. 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.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. return value the sorted typed array. examples using sort for more examples, see also the array.prototype.sort() method. let numbers = new uint8array([40, 1, 5, ...
... ...
TypedArray.prototype.toString() - JavaScript
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. ...
... 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. 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. ...
WebAssembly.Table.prototype.get() - JavaScript
examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. ...
...e method of the webassembly.table() object retrieves a function reference stored at a given index. syntax table.get(index); parameters index the index of the function reference you want to retrieve. return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instan...
TextDecoder.prototype.decode() - Web APIs
syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. ...
TextDecoder.prototype.encoding - Web APIs
it can be one of the following values: the recommended encoding for the web: 'utf-8'. the legacy single-byte encodings: 'ibm866', 'iso-8859-2', 'iso-8859-3', 'iso-8859-4', 'iso-8859-5', 'iso-8859-6', 'iso-8859-7', 'iso-8859-8'', 'iso-8859-8i', 'iso-8859-10', 'iso-8859-13', 'iso-8859-14', 'iso-8859-15', 'iso-8859-16', 'koi8-r', 'koi8-u', 'macintosh', 'windows-874', 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254', 'windows-1255', 'windows-1256', 'windows-1257', 'windows-1258', or 'x-mac-cyrillic'. the legacy multi-byte chinese (simplified) encodings: 'gbk', 'gb18030', and 'hz-gb-2312'. ...
TypeError: invalid Array.prototype.sort argument - JavaScript
the javascript exception "invalid array.prototype.sort argument" occurs when the argument of array.prototype.sort() isn't either undefined or a function which compares its operands. message typeerror: argument is not a function object (edge) typeerror: invalid array.prototype.sort argument (firefox) error type typeerror what went wrong? the argument of array.prototype.sort() is expected to be either undefined or a function which compares its operands. examples invalid cases [1, 3, 2].sort(5); // typeerror var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key] || 'asc'); // typeerror valid cases [1, 3, 2].sort(); // [1, 2, 3] var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3] ...
Array.prototype.concat() - JavaScript
...
Array.prototype.entries() - JavaScript
...
Array.prototype.flat() - JavaScript
...
Array.prototype.join() - JavaScript
array four times: using the default separator, then a comma and a space, then a plus and an empty string. var a = ['wind', 'water', 'fire']; a.join(); // 'wind,water,fire' a.join(', '); // 'wind, water, fire' a.join(' + '); // 'wind + water + fire' a.join(''); // 'windwaterfire' joining an array-like object the following example joins array-like object (arguments), by calling function.prototype.call on array.prototype.join. function f(a, b, c) { var s = array.prototype.join.call(arguments); console.log(s); // '1,a,true' } f(1, 'a', true); //expected output: "1,a,true" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.join' in that specification. ...
Array.prototype.keys() - JavaScript
send us a pull request. syntax arr.keys() return value a new array iterator object. examples key iterator doesn't ignore holes var arr = ['a', , 'c']; var sparsekeys = object.keys(arr); var densekeys = [...arr.keys()]; console.log(sparsekeys); // ['0', '2'] console.log(densekeys); // [0, 1, 2] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.keys' in that specification. ...
Array.prototype.length - JavaScript
r); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, <3 empty items> ] arr.foreach(element => console.log(element)); // 1 // 2 as you can see, the length property does not necessarily indicate the number of defined values in the array. see also relationship between length and numerical properties. property attributes of array.prototype.length writable yes enumerable no configurable no writable: if this attribute set to false, the value of the property cannot be changed. configurable: if this attribute set to false, any attempts to delete the property or change its attributes (writable, configurable, or enumerable) will fail. enumerable: if th...
Array.prototype.reverse() - JavaScript
console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object. the call to reverse() returns a reference to the reversed array-like object a. const a = {0: 1, 1: 2, 2: 3, length: 3}; console.log(a); // {0: 1, 1: 2, 2: 3, length: 3} array.prototype.reverse.call(a); //same syntax for using apply() console.log(a); // {0: 3, 1: 2, 2: 1, length: 3} specifications specification ecmascript (ecma-262)the definition of 'array.prototype.reverse' in that specification. ...
Array.prototype.sort() - JavaScript
...
Array.prototype.splice() - JavaScript
...
Array.prototype.toString() - JavaScript
ing 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. 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. ...
Array.prototype.unshift() - JavaScript
...
ArrayBuffer.prototype.byteLength - JavaScript
...
ArrayBuffer.prototype.slice() - JavaScript
. the range specified by the begin and end parameters is clamped to the valid index range for the current array. if the computed length of the new arraybuffer would be negative, it is clamped to zero. examples copying an arraybuffer const buf1 = new arraybuffer(8); const buf2 = buf1.slice(0); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.slice' in that specification. ...
BigInt.prototype.valueOf() - JavaScript
...
Boolean.prototype.valueOf() - JavaScript
...
DataView.prototype.buffer - JavaScript
...
DataView.prototype.byteLength - JavaScript
...
DataView.prototype.byteOffset - JavaScript
ed and cannot be changed. examples using the byteoffset property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 = new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specification. ...
DataView.prototype.getBigInt64() - JavaScript
...
DataView.prototype.getBigUint64() - JavaScript
s set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification. ...
DataView.prototype.getFloat32() - JavaScript
...
DataView.prototype.getFloat64() - JavaScript
...
DataView.prototype.getInt16() - JavaScript
...
DataView.prototype.getInt32() - JavaScript
...
DataView.prototype.getInt8() - JavaScript
...
DataView.prototype.getUint16() - JavaScript
...
DataView.prototype.getUint32() - JavaScript
...
DataView.prototype.getUint8() - JavaScript
...
DataView.prototype.setBigInt64() - JavaScript
e undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification. ...
DataView.prototype.setBigUint64() - JavaScript
undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification. ...
DataView.prototype.setFloat32() - JavaScript
rn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification. ...
DataView.prototype.setFloat64() - JavaScript
rn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification. ...
DataView.prototype.setInt16() - JavaScript
return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification. ...
DataView.prototype.setInt32() - JavaScript
return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification. ...
DataView.prototype.setInt8() - JavaScript
t. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification. ...
DataView.prototype.setUint16() - JavaScript
eturn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification. ...
DataView.prototype.setUint32() - JavaScript
eturn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification. ...
DataView.prototype.setUint8() - JavaScript
return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that specification. ...
Date.prototype[@@toPrimitive] - JavaScript
...
Date.prototype.getDate() - JavaScript
...
Date.prototype.getFullYear() - JavaScript
returns a four-digit number, for example, 1995. use this function to make sure a year is compliant with years after 2000. examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year. var today = new date(); var year = today.getfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getfullyear' in that specification. ...
Date.prototype.getHours() - JavaScript
or the given date according to local time. examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. let xmas95 = new date('december 25, 1995 23:15:30'); let hours = xmas95.gethours(); console.log(hours); // 23 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gethours' in that specification. ...
Date.prototype.getMilliseconds() - JavaScript
...
Date.prototype.getMinutes() - JavaScript
given date according to local time. examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var minutes = xmas95.getminutes(); console.log(minutes); // 15 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getminutes' in that specification. ...
Date.prototype.getMonth() - JavaScript
intl.datetimeformat() with an options parameter. using this method, internationalization is made easier: var options = { month: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // december console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // dezember specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmonth' in that specification. ...
Date.prototype.getSeconds() - JavaScript
given date according to local time. examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var seconds = xmas95.getseconds(); console.log(seconds); // 30 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getseconds' in that specification. ...
Date.prototype.getTime() - JavaScript
alculate the executing time of some operations. see also date.now() to prevent instantiating unnecessary date objects. var end, start; start = new date(); for (var i = 0; i < 1000; i++) { math.sqrt(i); } end = new date(); console.log('operation took ' + (end.gettime() - start.gettime()) + ' msec'); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gettime' in that specification. ...
Date.prototype.getTimezoneOffset() - JavaScript
...
Date.prototype.getUTCDate() - JavaScript
...
Date.prototype.getUTCDay() - JavaScript
...
Date.prototype.getUTCFullYear() - JavaScript
...
Date.prototype.getUTCHours() - JavaScript
...
Date.prototype.getUTCMilliseconds() - JavaScript
ix epoch time. to get total milliseconds since 1970/01/01, use the method ".gettime()". examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. var today = new date(); var milliseconds = today.getutcmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmilliseconds' in that specification. ...
Date.prototype.getUTCMinutes() - JavaScript
...
Date.prototype.getUTCMonth() - JavaScript
...
Date.prototype.getUTCSeconds() - JavaScript
...
Date.prototype.getYear() - JavaScript
...
Date.prototype.setDate() - JavaScript
...
Date.prototype.setFullYear() - JavaScript
...
Date.prototype.setHours() - JavaScript
...
Date.prototype.setMilliseconds() - JavaScript
...
Date.prototype.setMinutes() - JavaScript
...
Date.prototype.setMonth() - JavaScript
turn 2nd march 2016. this is because in 2016 february had 29 days. examples using setmonth() var thebigday = new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth = new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar 02 2016 00:00:00 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmonth' in that specification. ...
Date.prototype.setSeconds() - JavaScript
...
Date.prototype.setTime() - JavaScript
...
Date.prototype.setUTCDate() - JavaScript
...
Date.prototype.setUTCFullYear() - JavaScript
...
Date.prototype.setUTCHours() - JavaScript
...
Date.prototype.setUTCMilliseconds() - JavaScript
ate information in the date object accordingly. for example, if you use 1100 for millisecondsvalue, the seconds stored in the date object will be incremented by 1, and 100 will be used for milliseconds. examples using setutcmilliseconds() var thebigday = new date(); thebigday.setutcmilliseconds(500); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmilliseconds' in that specification. ...
Date.prototype.setUTCMinutes() - JavaScript
...
Date.prototype.setUTCMonth() - JavaScript
...
Date.prototype.setUTCSeconds() - JavaScript
...
Date.prototype.setYear() - JavaScript
year for dateobj is set to 1900 + yearvalue. otherwise, the year for dateobj is set to yearvalue. examples using setyear() the first two lines set the year to 1996. the third sets the year to 2000. var thebigday = new date(); thebigday.setyear(96); thebigday.setyear(1996); thebigday.setyear(2000); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setyear' in that specification. ...
Date.prototype.toDateString() - JavaScript
...
Date.prototype.toGMTString() - JavaScript
...
Date.prototype.toJSON() - JavaScript
g()) representing the date object's value. this method is generally intended to, by default, usefully serialize date objects during json serialization. examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tojson' in that specification. ...
Date.prototype.toLocaleDateString() - JavaScript
.log(date.tolocaledatestring('de-de', options)); // → "donnerstag, 20. dezember 2012" // an application may want to use utc and make that visible options.timezone = 'utc'; options.timezonename = 'short'; console.log(date.tolocaledatestring('en-us', options)); // → "thursday, december 20, 2012, gmt" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocaledatestring' in that specification. ecmascript internationalization api (ecma-402)the definition of 'date.prototype.tolocaledatestring' in that specification. ...
Date.prototype.toTimeString() - JavaScript
...
Date.prototype.toUTCString() - JavaScript
to the platform. the most common return value was an rfc-1123 formatted date stamp, which is a slightly updated version of rfc-822 date stamps. examples using toutcstring() let today = new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toutcstring' in that specification. ...
Date.prototype.valueOf() - JavaScript
method returns the primitive value of a date object. syntax dateobj.valueof() return value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date. description the valueof() method returns the primitive value of a date object as a number data type, the number of milliseconds since midnight 01 january, 1970 utc. this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification. ...
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.prototyp...
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. ...
FinalizationRegistry.prototype.register() - JavaScript
...
FinalizationRegistry.prototype.unregister() - JavaScript
eld by this `thingy` instance. */ release() { if (this.#file) { this.#registry.unregister(this.#file); // ^^^^^^^^^^−−−−− unregister token file.close(this.#file); this.#file = null; } } } specifications specification weakrefsthe definition of 'finalizationregistry.prototype.unregister' in that specification. ...
Function.prototype.call() - JavaScript
...
Generator.prototype.next() - JavaScript
...
Generator.prototype.return() - JavaScript
...
Generator.prototype.throw() - JavaScript
h block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new error('something went wrong')); // "error caught!" // { value: 42, done: false } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.throw' in that specification. ...
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
the intl.datetimeformat.prototype.formatrange() formats a date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat 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 intl.datetimeformat.prototype.formatrange(startdate, enddate) examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat. let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); let date3 = new dat...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
the intl.datetimeformat.prototype.formatrangetoparts() method allows locale-specific tokens representing each part of the formatted date range produced by datetimeformat formatters. 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 intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); // > 'wed, 10 ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
Intl.Locale.prototype.baseName - JavaScript
description an intl.locale object represents a parsed local and options for that locale. the basename property returns basic, core information about the locale in the form 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. ...
Intl.Locale.prototype.calendar - JavaScript
description the calendar property returns the part of the locale that indicates the locale's calendar era. while most of the world uses the gregorian calendar, there are several regional calendar eras used around the world. the following table shows all the valid unicode calendar key strings, along with a description of the calendar era they represent. ...
Intl.Locale.prototype.caseFirst - JavaScript
description a locale's collation rules are used to determine how strings are ordered in that locale. certain locales use a character's case (uppercase or lowercase) in the collation process. this additional rule can be expressed in a locale's casefirst property. there are 3 values that the casefirst property can have, outlined in the table below. casefirst values value description upper upper case to be sorted before lower case. lower lower case to be sorted before upper case. false no special case ordering. ...
Intl.Locale.prototype.collation - JavaScript
description collation is the process of ordering strings of characters. it is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. while the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. the collation property helps to make it easier for javascript programmers to access the collation type used by a particular locale. below is a table with the available collation types, taken from the unicode collation specification. ...
Intl.Locale.prototype.hourCycle - JavaScript
description there are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. the hourcycle property makes it easier for javascript programmers to access the clock type used by a particular locale. like other additional locale data, hour cycle type is an extension subtag, which extends the data contained in a locale string. the hour cycle type can have several different values, which are listed in the table below. valid hour cycle types hour cycle type description h12 hour system using 1–12; corresponds to 'h' in patterns. ...
Intl.Locale.prototype.language - JavaScript
description language is one of the core features of a locale. the unicode specification treats the language identifier of a locale as the language and the region together (to make a distiction between dialects and variations, e.g. british english vs. american english). the language property of a locale returns strictly the locale's language subtag. examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag. ...
Intl.Locale.prototype.maximize() - JavaScript
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.maximize() return value a locale instance whose basename property returns the result of the add likely subtags algorithm executed against locale.basename. description sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete langauage id. the add likely subtags algorithm gives us this functionality. ...
Intl.Locale.prototype.minimize() - JavaScript
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.minimize() return value a locale instance whose basename property returns the result of the remove likely subtags algorithm executed against locale.basename. description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). ...
Intl.Locale.prototype.numberingSystem - JavaScript
description a numeral system is a system for expressing numbers. the numberingsystem property helps to represent the different numeral systems used by various countries, regions, and cultures around the world. as with most internationalization schemas, the numeral systems that can be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. ...
Intl.Locale.prototype.numeric - JavaScript
description like intl.locale.casefirst, numeric represents a modification to the collation rules utilized by the locale. numeric is a boolean value, which means that it can be either true or false. if numeric is set to false, there will be no special handling of numeric values in strings. if numeric is set to true, then the locale will take numeric characters into account when collating strings. this special numeric handling means that sequences of decimal digits will be compared as numbers. for example, the string "a-21" will be considered less than "a-123". ...
Intl.Locale.prototype.region - JavaScript
description the region is an essential part of the locale identifier, as it places the locale in a specific area of the world. knowing the locale's region is vital to identifying differences between locales. for example, english is spoken in the united kingdom and the united states of america, but there are differences in spelling and other language conventions between those two countries. knowing the locale's region helps javascript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world. ...
Intl.Locale.prototype.script - JavaScript
description a script, sometimes called writing system, is one of the core attributes of a locale. it indicates the set of symbols, or glyphs, that are used to write a particular language. for instance, the script associated with english is latin, whereas the script typically associated with korean is hangul. in many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. there are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete unicode language identifier. ...
Intl.Locale.prototype.toString() - JavaScript
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. ...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
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 relativetimeformat.format(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. ...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
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 relativetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object. ...
Map.prototype[@@iterator]() - JavaScript
...
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. ...
Map.prototype.clear() - JavaScript
ctive-examples and send us a pull request. syntax mymap.clear(); return value undefined. examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification. ...
Map.prototype.delete() - JavaScript
n the map object existed and has been removed, or false if the element does not exist. examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true. successfully removed. mymap.has('bar'); // returns false. the "bar" element is no longer present. specifications specification ecmascript (ecma-262)the definition of 'map.prototype.delete' in that specification. ecmascript 2015 (6th edition, ecma-262)the definition of 'map.prototype.delete' in that specification. ...
Map.prototype.entries() - JavaScript
t. examples using entries() let mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (ecma-262)the definition of 'map.prototype.entries' in that specification. ...
Map.prototype.forEach() - JavaScript
...
Map.prototype.get() - JavaScript
nt to return from the map object. return value the element associated with the specified key, or undefined if the key can't be found in the map object. examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification. ...
Map.prototype.has() - JavaScript
...
Map.prototype.keys() - JavaScript
value a new map iterator object. examples using keys() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in that specification. ...
Map.prototype.set() - JavaScript
...
Map.prototype.size - JavaScript
...
Map.prototype.values() - JavaScript
a new map iterator object. examples using values() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.values' in that specification. ...
Number.prototype.toExponential() - JavaScript
...
Number.prototype.valueOf() - JavaScript
r object. description this method is usually called internally by javascript and not explicitly in web code. examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification. ...
Object.prototype.__defineGetter__() - JavaScript
...
Object.prototype.__defineSetter__() - JavaScript
...
Object.prototype.__lookupSetter__() - JavaScript
...
Promise.prototype.finally() - JavaScript
...
RegExp.prototype.compile() - JavaScript
compile method is deprecated. you can just use the regexp constructor to achieve the same effect. examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag. var regexobj = new regexp('foo', 'gi'); regexobj.compile('new foo', 'g'); specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.compile' in that specification. ...
RegExp.prototype.exec() - JavaScript
match in a specified string. returns a result array, or null. javascript regexp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). they store a lastindex from the previous match. using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with string.prototype.match(). a newer function has been proposed to simplify matching multiple parts of a string (with capture groups): string.prototype.matchall(). if you are executing a match simply to find true or false, use regexp.prototype.test() method or string.prototype.search() instead. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interacti...
Set.prototype[@@iterator]() - JavaScript
...
Set.prototype.add() - JavaScript
l request. syntax myset.add(value); parameters value the value of the element to add to the set object. return value the set object. examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification. ...
Set.prototype.clear() - JavaScript
interactive-examples and send us a pull request. syntax myset.clear(); return value undefined. examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification. ...
Set.prototype.delete() - JavaScript
n object from a set. const setobj = new set(); // create a new set. setobj.add({x: 10, y: 20}); // add object in the set. setobj.add({x: 20, y: 30}); // add object in the set. // delete any point with `x > 10`. setobj.foreach(function(point){ if (point.x > 10){ setobj.delete(point) } }) specifications specification ecmascript (ecma-262)the definition of 'set.prototype.delete' in that specification. ...
Set.prototype.entries() - JavaScript
order. examples using entries() var myset = new set(); myset.add('foobar'); myset.add(1); myset.add('baz'); var setiter = myset.entries(); console.log(setiter.next().value); // ["foobar", "foobar"] console.log(setiter.next().value); // [1, 1] console.log(setiter.next().value); // ["baz", "baz"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.entries' in that specification. ...
Set.prototype.forEach() - JavaScript
...
Set.prototype.has() - JavaScript
...
Set.prototype.size - JavaScript
pull request. description the value of size is an integer representing how many entries the set object has. a set accessor function for size is undefined; you cannot change this property. examples using size var myset = new set(); myset.add(1); myset.add(5); myset.add('some text') myset.size; // 3 specifications specification ecmascript (ecma-262)the definition of 'set.prototype.size' in that specification. ...
Set.prototype.values() - JavaScript
in the given set, in insertion order. examples using values() var myset = new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next().value); // "foo" console.log(setiter.next().value); // "bar" console.log(setiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.values' in that specification. ...
SharedArrayBuffer.prototype.byteLength - JavaScript
...
String.prototype[@@iterator]() - JavaScript
...
String.prototype.anchor() - JavaScript
...
String.prototype.big() - JavaScript
...
String.prototype.blink() - JavaScript
...
String.prototype.bold() - JavaScript
...
String.prototype.charAt() - JavaScript
...
String.prototype.charCodeAt() - JavaScript
...
String.prototype.concat() - JavaScript
t('kevin', '. have a nice day.')) // hello, kevin. have a nice day. let greetlist = ['hello', ' ', 'venkat', '!'] "".concat(...greetlist) // "hello venkat!" "".concat({}) // [object object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "true" "".concat(4, 5) // "45" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.concat' in that specification. ...
String.prototype.fixed() - JavaScript
<tt> html element. description the fixed() method embeds a string in a <tt> tag: "<tt>str</tt>". examples using fixed() the following example uses the fixed method to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.fixed()); // "<tt>hello, world</tt>" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fixed' in that specification. ...
String.prototype.fontcolor() - JavaScript
...
String.prototype.fontsize() - JavaScript
...
String.prototype.italics() - JavaScript
...
String.prototype.lastIndexOf() - JavaScript
...
String.prototype.link() - JavaScript
...
String.prototype.normalize() - JavaScript
...
String.prototype.padEnd() - JavaScript
...
String.prototype.padStart() - JavaScript
...
String.prototype.replace() - JavaScript
e f2c() function. f2c() then returns the celsius number. this function approximates perl's s///e flag. function f2c(x) { function convert(str, p1, offset, s) { return ((p1 - 32) * 5/9) + 'c'; } let s = string(x); let test = /(-?\d+(?:\.\d*)?)f\b/g; return s.replace(test, convert); } specifications specification ecmascript (ecma-262)the definition of 'string.prototype.replace' in that specification. ...
String.prototype.replaceAll() - JavaScript
...
String.prototype.slice() - JavaScript
...
String.prototype.small() - JavaScript
...
String.prototype.split() - JavaScript
...
String.prototype.strike() - JavaScript
...
String.prototype.sub() - JavaScript
...
String.prototype.substring() - JavaScript
p if olds is itself a substring of news — for example, if you attempted to replace 'world' with 'otherworld' here. a better method for replacing strings is as follows: function replacestring(olds, news, fulls) { return fulls.split(olds).join(news) } the code above serves as an example for substring operations. if you need to replace substrings, most of the time you will want to use string.prototype.replace(). specifications specification ecmascript (ecma-262)the definition of 'string.prototype.substring' in that specification. ...
String.prototype.sup() - JavaScript
...
String.prototype.toLowerCase() - JavaScript
senting the calling string converted to lower case. description the tolowercase() method returns the value of the string converted to lower case. tolowercase() does not affect the value of the string str itself. examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' 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. ...
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.prototype[@@toPrimitive] - JavaScript
n object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. examples using @@toprimitive const sym = symbol("example"); sym === sym[symbol.toprimitive](); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.@@toprimitive' in that specification. ...
Symbol.prototype.valueOf() - JavaScript
...
TypedArray.prototype[@@iterator]() - JavaScript
...
TypedArray.prototype.buffer - JavaScript
his property. the value is established when the typedarray is constructed and cannot be changed. typedarray is one of the typedarray objects. examples using the buffer property var buffer = new arraybuffer(8); var uint16 = new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification. ...
TypedArray.prototype.byteLength - JavaScript
...
TypedArray.prototype.byteOffset - JavaScript
is one of the typedarray objects. examples using the byteoffset property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 = new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification. ...
TypedArray.prototype.entries() - JavaScript
...
TypedArray.prototype.find() - JavaScript
there is no prime number). function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification. ...
TypedArray.prototype.keys() - JavaScript
...
TypedArray.prototype.length - JavaScript
...
TypedArray.prototype.set() - JavaScript
ex 0). exceptions a rangeerror, if the offset is set such as it would store beyond the end of the typed array. examples using set() var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in that specification. ...
TypedArray.prototype.subarray() - JavaScript
inal object and vice versa. examples using the subarray method var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] var sub = uint8.subarray(0,4); console.log(sub); // uint8array [ 1, 2, 3, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.subarray' in that specification. ...
TypedArray.prototype.values() - JavaScript
...
WeakMap.prototype.delete() - JavaScript
...
WeakMap.prototype.get() - JavaScript
akmap object. return value the element associated with the specified key in the weakmap object. if the key can't be found, undefined is returned. examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo". wm.get('baz'); // returns undefined. specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.get' in that specification. ...
WeakMap.prototype.has() - JavaScript
resence in the weakmap object. return value boolean returns true if an element with the specified key exists in the weakmap object; otherwise false. examples using the has method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification. ...
WeakMap.prototype.set() - JavaScript
...
WeakRef.prototype.deref() - JavaScript
...
WeakSet.prototype.add() - JavaScript
...
WeakSet.prototype.delete() - JavaScript
...
WeakSet.prototype.has() - JavaScript
the weakset. return value boolean returns true if an element with the specified value exists in the weakset object; otherwise false. examples using the has method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // returns true myset.has(obj); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification. ...
WebAssembly.Instance.prototype.exports - JavaScript
instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process. we then call an exported webassembly function that is exported by the instance. ...
WebAssembly.Memory.prototype.buffer - JavaScript
examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Table.prototype.grow() - JavaScript
syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. ...
WebAssembly.Table.prototype.length - JavaScript
the number of elements in the table. syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification. browser compatibility the compatibility table on this page is generated from structured data. ...
Details of the object model - JavaScript
« previousnext » javascript is an object-based language based on prototypes, rather than being class-based. because of this different basis, it can be less apparent how javascript allows you to create hierarchies of objects and to have inheritance of properties and their values. this chapter attempts to clarify the situation. this chapter assumes that you are already somewhat familiar with javascript and that you have used javascript functions to create simple objects. class-based vs. prototype-based languages class-based object-oriented languages, such as java and c++, are founded on the concept of two distinct entities: classes and instances. a class defines all of the properties that characterize a certain set of objects (considering methods and fields in java, or member...
...ar member in a set of objects it describes. for example, the employee class could represent the set of all employees. an instance, on the other hand, is the instantiation of a class; that is. for example, victoria could be an instance of the employee class, representing a particular individual as an employee. an instance has exactly the same properties of its parent class (no more, no less). ...
...all employees. an instance, on the other hand, is the instantiation of a class; that is. for example, victoria could be an instance of the employee class, representing a particular individual as an employee. an instance has exactly the same properties of its parent class (no more, no less). a prototype-based language, such as javascript, does not make this distinction: it simply has objects. a prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. any object can specify its own properties, either when you create it or at run time. in addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties. defining a class in cl...
...And 63 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setfo...
... this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g ...
... && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g = green | 0; this.b = blue | 0; if (this.isvalidrgbvalue(alpha) === true) this.a = alpha | 0; }; color.prototype.setbyname = function setbyname(name, value) { if (name === 'r' || name === 'g' || name === 'b') { if(this.isvalidrgbvalue(value) === false) return; this[name] = value; this.updatehsx(); } }; color.prototype.sethsv = function sethsv(hue, saturation, value) { this.hue = hue; this.saturation = saturation; this.value = value; this.hsvtorgb(); }; color.prototype.sethsl ...
...And 53 more matches
Color picker tool - CSS: Cascading Style Sheets
(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setfo...
... this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g ...
... && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g = green | 0; this.b = blue | 0; if (this.isvalidrgbvalue(alpha) === true) this.a = alpha | 0; }; color.prototype.setbyname = function setbyname(name, value) { if (name === 'r' || name === 'g' || name === 'b') { if(this.isvalidrgbvalue(value) === false) return; this[name] = value; this.updatehsx(); } }; color.prototype.sethsv = function sethsv(hue, saturation, value) { this.hue = hue; this.saturation = saturation; this.value = value; this.hsvtorgb(); }; color.prototype.sethsl ...
...And 40 more matches
JavaScript Daemons Management - Archive of obsolete content
s.rate = math.floor(nrate); } if (nlen > 0) { this.length = math.floor(nlen); } if (fonstart) { this.onstart = fonstart; } if (finit) { this.onstop = finit; finit.call(oowner, this.index, this.length, this.backw); } } /* create the daemon.blank() constructor and the global daemon.context object */ daemon.blank = function () {}; daemon.context = daemon.blank.prototype; /* make love with the gc :-) */ daemon.blank.prototype = /* important! */ daemon.prototype; daemon.context.constructor = object; /* these properties can be manually reconfigured after the creation of the daemon */ daemon.prototype.owner = daemon.context; daemon.prototype.task = null; daemon.prototype.rate = 100; daemon.prototype.length = infinity; daemon.prototype.reversals =...
...e with the gc :-) */ daemon.blank.prototype = /* important! ...
....prototype = /* important! ...
...And 34 more matches
Index
d that does not need to be marked for gc from jspropertyspec::name or jsfunctionspec::name. the resulting jsid, on success, is either an interned string or a well-known symbol; either way it is immune to gc so there is no need to visit *idp during gc marking.. 64 js::protokeytoid jsapi reference, reference, référence(2), spidermonkey js::protokeytoid converts a specified js prototype key key, to a js id. js::protokeytoid stores a jsid to *idp. 65 js::remove*root jsapi reference, obsolete, reference, référence(2), spidermonkey js::remove*root removes the variable that rp points to from the garbage collector's root set. 66 js::rooted jsapi reference, reference, référence(2), spidermonkey here, ptr represents the private member of js...
...e macros providing equivalent functionality are deprecated. 126 jsnewenumerateop jsapi reference, reference, référence(2), spidermonkey from spidermonkey 38, jsnewenumerateop is the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are called in order. the properties each op adds to the properties vector are added to the set of values the for-in loop will iterate over. all of this is nonstandard. 127 jsnewresolveop jsapi reference, obsolete, spidermonkey like jsresolveop, but flags provide contextual information about the property access. 128 ...
...e infallible, so required slots must be pre-allocated, or implementations must suppress out-of-memory errors. the native ops (js_objectops, see js/src/jsobj.cpp) access slots reserved by including a call to the jsclass_has_reserved_slots(n) macro in the jsclass.flags initializer. 138 jsobjectops.lookupproperty jsapi reference, obsolete, spidermonkey look for id in obj and its prototype chain, returning js_false on error or exception, js_true on success. on success, return null in *propp if id was not found. if id was found, return the first object searching from obj along its prototype chain in which id names a direct property in *objp, and return a non-null, opaque property pointer in *propp. 139 jsobjectops.newobjectmap jsapi reference, obsolete, spidermonkey ...
...And 29 more matches
String - JavaScript
a constructor, which is usually more useful. static methods string.fromcharcode(num1 [, ...[, numn]]) returns a string created by using the specified sequence of unicode values. string.fromcodepoint(num1 [, ...[, numn) returns a string created by using the specified sequence of code points. string.raw() returns a string created from a raw template string. ...
......[, numn]]) returns a string created by using the specified sequence of unicode values. string.fromcodepoint(num1 [, ...[, numn) returns a string created by using the specified sequence of code points. string.raw() returns a string created from a raw template string. instance properties string.prototype.length reflects the length of the string. read-only. instance methods string.prototype.charat(index) returns the character (exactly one utf-16 code unit) at the specified index. ...
...nt(num1 [, ...[, numn) returns a string created by using the specified sequence of code points. string.raw() returns a string created from a raw template string. instance properties string.prototype.length reflects the length of the string. read-only. instance methods string.prototype.charat(index) returns the character (exactly one utf-16 code unit) at the specified index. string.prototype.charcodeat(index) returns a number that is the utf-16 code unit value at the given index. ...
...And 23 more matches
New in JavaScript 1.3 - Archive of obsolete content
1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- javascript for navigator 4.5. ...
... and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- javascript for navigator 4.5. ...
...ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- javascript for navigator 4.5. ...
...And 21 more matches
Object - JavaScript
the object class represents one of javascript's data types. it is used to store various keyed collections and more complex entities. objects can be created using the object() constructor or the object initializer / literal syntax. description nearly all objects in javascript are instances of object; a typical object inherits properties (including methods) from object.prototype, although these properties may be shadowed (a.k.a. ...
...yntax. description nearly all objects in javascript are instances of object; a typical object inherits properties (including methods) from object.prototype, although these properties may be shadowed (a.k.a. overridden). however, an object may be deliberately created for which this is not true (e.g. by object.create(null)), or it may be altered so that this is no longer true (e.g. with object.setprototypeof). changes to the object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. this provides a very powerful although potentially dangerous mechanism to override or extend object behavior. the object constructor creates an object wrapper for the given value. if the val...
...ise, it will return an object of a type that corresponds to the given value. if the value is an object already, it will return the value. when called in a non-constructor context, object behaves identically to new object(). see also the object initializer / literal syntax. deleting a property from an object there isn't any method in an object itself to delete its own properties (such as map.prototype.delete()). to do so, one must use the delete operator. constructor object() creates a new object object. it is a wrapper for the given value. static methods object.assign() copies the values of all enumerable own properties from one or more source objects to a target object. object.create() creates a new object with the specified prototype object and properties. object.definepropert...
...And 21 more matches
Classes and Inheritance - Archive of obsolete content
not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. classes in javascript are defined using constructor functions. ...
...ossible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. classes in javascript are defined using constructor functions. each constructor function has an associated object, known as its prototype, which is shared between all instances of that class. we will show how to define classes using constructors, and how to use prototypes to efficiently define member functions on each instance. classical inheritance can be implemented in javascript using constructors and prototypes. we will show how to make inheritance work correctly with respect to constructors, prototypes, and the instanceof operator, and how to override methods in subclasses. the sdk uses a special constructor internally, known as class, to create constructors...
...ly legal to perform ordinary function calls on them. in fact, some people (including the add-on sdk team) prefer to use constructors this way. however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function shape(x, y) { if (!this) return new shape(x, y); this.x = x; this.y = y; } prototypes every object has an implicit property, known as its prototype. when javascript looks for a property, it first looks for it in the object itself. if it cannot find the property there, it looks for it in the object's prototype. if the property is found on the prototype, the lookup succeeds, and javascript pretends that it found the property on the original object. every function has an explicit p...
...And 20 more matches
Box-shadow generator - CSS: Cascading Style Sheets
ibe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function(){ boxshadow.init(); }); var boxshadow = (function boxshadow() { function getelembyid(id) { return document.getelementbyid(id); } /** * rgba color class */ function color() { this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log("typeof instance not color"); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; } color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (red != undefined) this.r = red |...
...rototype.setrgba = function setrgba(red, green, blue, alpha) { if (red != undefined) this.r = red | 0; if (green != undefined) this.g = green | 0; if (blue != undefined) this.b = blue | 0; if (alpha != undefined) this.a = alpha | 0; } /** * hsv/hsb (hue, saturation, value / brightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 */ color.prototype.sethsv = function sethsv(hue, saturation, value) { this.hue = hue; this.saturation = saturation; this.value = value; this.updatergb(); } color.prototype.updatergb = function updatergb() { var sat = this.saturation / 100; var value = this.value / 100; var c = sat * value; var h = this.hue / 60; var x = c * (1 - math.abs(h % 2 - 1)); var m = value - c; var precision = 255; ...
... + m) * precision; m = m * precision; if (h >= 0 && h < 1) { this.setrgba(c, x, m); return; } if (h >= 1 && h < 2) { this.setrgba(x, c, m); return; } if (h >= 2 && h < 3) { this.setrgba(m, c, x); return; } if (h >= 3 && h < 4) { this.setrgba(m, x, c); return; } if (h >= 4 && h < 5) { this.setrgba(x, m, c); return; } if (h >= 5 && h < 6) { this.setrgba(c, m, x); return; } } color.prototype.updatehsv = function updatehsv() { var red = this.r / 255; var green = this.g / 255; var blue = this.b / 255; var cmax = math.max(red, green, blue); var cmin = math.min(red, green, blue); var delta = cmax - cmin; var hue = 0; var saturation = 0; if (delta) { if (cmax === red ) { hue = ((green - blue) / delta); } if (cmax === green ) { hue = 2 + (blue - red) / delta; } ...
...And 18 more matches
TypedArray - JavaScript
es and methods that can be used with any typed array containing elements of any type. 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. ...
... the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description ecmascript 2015 defines a typedarray constructor that serves as the [[prototype]] of all typedarray constructors. this constructor is not directly exposed: there is no global %typedarray% or typedarray property. it is only directly accessible through object.getprototypeof(int8array) and similar. all typedarrays constructors inherit common properties from the %typedarray% constructor function. additionally, all typed array prototypes (typedarray.prototype) have %typedarray%.prototype as their [[prototype]]. the %typedarray% constructor on its own is not particularly useful. calling it or using it in a new expression will throw a typeerror, except when used du...
...ypedarray% is only useful to polyfill functions or properties onto all typedarray constructors. when creating an instance of a typedarray (e.g. int8array), an array buffer is created internally in memory or, if an arraybuffer object is given as constructor argument, then this is used instead. the buffer address is saved as an internal property of the instance and all the methods of %typedarray%.prototype, i.e. set value and get value etc., operate on that array buffer address. typedarray objects type value range size in bytes description web idl type equivalent c type int8array -128 to 127 1 8-bit two's complement signed integer byte int8_t uint8array 0 to 255 1 8-bit unsigned integer octet uint8_t uint8clamped...
...And 18 more matches
core/heritage - Archive of obsolete content
s of machinery being exposed: // defining a simple class function dog(name) { // classes are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. ...
...are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof dog)) return new dog(name); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. this is too much machinery exposed. ...
...calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof dog)) return new dog(name); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. this is too much machinery exposed. ...
...And 17 more matches
Date - JavaScript
january, 1970, 00:00:00 utc, with leap seconds ignored. note: parsing of strings with date.parse is strongly discouraged due to browser differences and inconsistencies. date.utc() accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored. ...
...iscouraged due to browser differences and inconsistencies. date.utc() accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored. instance methods date.prototype.getdate() returns the day of the month (1–31) for the specified date according to local time. date.prototype.getday() returns the day of the week (0–6) for the specified date according to local time. ...
... longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored. instance methods date.prototype.getdate() returns the day of the month (1–31) for the specified date according to local time. date.prototype.getday() returns the day of the week (0–6) for the specified date according to local time. date.prototype.getfullyear() returns the year (4 digits for 4-digit years) of the specified date according to local time. date.prototype.gethours() returns the hour (0–23) in the specified date according to local time. ...
...And 16 more matches
Property cache
c,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: basic layout guarantee — if at time t0 the object x has shape s and at time t1 the object y has shape s, and no shape-regenerating gc occurred, then y at t1 has the same jsclass, jsobjectops, prototype, and property specs as x had at t0. to be more precise regarding property specs, y's properties hav...
...ty specs as x had at t0. to be more precise regarding property specs, y's properties have the same names, getters, setters, property attributes, and slot offsets, and they are in the same order, as x's properties at t0. furthermore, y at t1 has the same number of fixed slots that x had at t0, and either both have a slot array or neither does. ...
...recise regarding property specs, y's properties have the same names, getters, setters, property attributes, and slot offsets, and they are in the same order, as x's properties at t0. furthermore, y at t1 has the same number of fixed slots that x had at t0, and either both have a slot array or neither does. ...
...And 15 more matches
Object.create() - JavaScript
the object.create() method creates a new object, using an existing object as the prototype of the newly created 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 object.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the newly-created object. propertiesobject optional if specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. thes...
... exceptions the proto parameter has to be either null or an object excluding primitive wrapper objects. if proto is neither of these a typeerror is thrown. ...
... // create "null" object (same as before) ocn.tostring = object.tostring; // since new object lacks method then try assigning it directly from standard-object > ocn.tostring // shows "tostring() { [native code] }" -- missing method seems to be there now > ocn.tostring == object.tostring // shows "true" -- method seems to be same as the standard object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of all these problems) and one cannot be directly added: ocn = object.create( null ); // create "null" object (same as before) ocn.prototype.tostring = object.tostring; // error:...
...And 15 more matches
Inheritance in JavaScript - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects). objective: to understand how it is possible to implement inheritance in javascript. prototypal inheritance so far we have seen some inheritance in action — we have seen how prototype chains work, and how members are inherited going up a chain. but mostly this has involved built-in browser functions. how do we create an object in javascript that inherits from another object? let's explore how to do this with a concrete example. getting started first of all, make yourself a local copy of our oojs-class-inheritance-start.html file (see it running live also). inside here you'l...
...he same person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor: function person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; the methods are all defined on the constructor's prototype. for example: person.prototype.greeting = function() { alert('hi! i\'m ' + this.name.first + '.'); }; note: in the source code, you'll also see bio() and farewell() methods defined. later you'll see how these can be inherited by other constructors. say we wanted to create a teacher class, like the one we described in our initial object-oriented definition, which inherits all the members fr...
...herit the width and height properties by doing this (as well as the other steps described below, of course): function blueglassbrick() { brick.call(this); this.opacity = 0.5; this.color = 'blue'; } note that we've only specified this inside call() — no other parameters are required as we are not inheriting any properties from the parent that are set via parameters. ...
...And 14 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
ronments like gnome (one of the most popular guis for gnu/linux operating systems), and others. overview javascript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. its syntax is based on the java and c languages — many structures from those languages apply to javascript as well. javascript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and es2015 classes). javascript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object. let's start off by looking at the building blocks of any language: the types. javascript programs manipulate values, and those values all belong to a type. jav...
...ld be preferred at all times. object literal syntax can be used to initialize an object in its entirety: var obj = { name: 'carrot', for: 'max', // 'for' is a reserved word, use '_for' instead. details: { color: 'orange', size: 12 } }; attribute access can be chained together: obj.details.color; // orange obj['details']['size']; // 12 the following example creates an object prototype(person) and an instance of that prototype(you). function person(name, age) { this.name = name; this.age = age; } // define an object var you = new person('you', 24); // we are creating a new person named "you" aged 24. once created, an object's properties can again be accessed in one of two ways: // dot notation obj.name = 'simon'; var name = obj.name; and... // bracket notation obj[...
...ed to set and get properties with names that are reserved words: obj.for = 'simon'; // syntax error, because 'for' is a reserved word obj['for'] = 'simon'; // works fine starting in ecmascript 5, reserved words may be used as object property names "in the buff". this means that they don't need to be "clothed" in quotes when defining object literals. see the es5 spec. for more on objects and prototypes see object.prototype. for an explanation of object prototypes and the object prototype chains see inheritance and the prototype chain. starting in ecmascript 2015, object keys can be defined by the variable using bracket notation upon being created. {[phonetype]: 12345} is possible instead of just var userphone = {}; userphone[phonetype] = 12345. arrays arrays in javascript are actually a s...
...And 13 more matches
Uint8ClampedArray - JavaScript
string value of the constructor name. in the case of the uint8clampedarray type: "uint8clampedarray". static methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments. see also array.of(). ...
...() creates a new uint8clampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments. see also array.of(). instance properties uint8clampedarray.prototype.buffer returns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only. uint8clampedarray.prototype.bytelength returns the length (in bytes) of the uint8clampedarray from the start of its arraybuffer. ...
...of arguments. see also array.of(). instance properties uint8clampedarray.prototype.buffer returns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only. uint8clampedarray.prototype.bytelength returns the length (in bytes) of the uint8clampedarray from the start of its arraybuffer. fixed at construction time and thus read only. uint8clampedarray.prototype.byteoffset returns the offset (in bytes) of the uint8clampedarray from the start of its arraybuffer. fixed at construction time and thus read only. uint8clampedarray.prototype.length returns the number of elements hold in the uintclamped8array. fixed at construction time and thus read only. ...
...And 12 more matches
Array - JavaScript
neither the length of a javascript array nor the types of its elements are fixed. since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, javascript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. ...
... the constructor function is used to create derived objects. static methods array.from() creates a new array instance from an array-like or iterable object. array.isarray() returns true if the argument is an array, or false otherwise. array.of() creates a new array instance with a variable number of arguments, regardless of number or type of the arguments. ...
...methods array.from() creates a new array instance from an array-like or iterable object. array.isarray() returns true if the argument is an array, or false otherwise. array.of() creates a new array instance with a variable number of arguments, regardless of number or type of the arguments. instance properties array.prototype.length reflects the number of elements in an array. ...
...And 11 more matches
BigInt64Array - JavaScript
y.name returns the string value of the constructor name. in the case of the bigint64array type, this is "bigint64array". static methods bigint64array.from() creates a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a variable number of arguments. see also array.of(). ...
...int64array.from() creates a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a variable number of arguments. see also array.of(). instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array. this is fixed at construction time and thus read only. bigint64array.prototype.bytelength returns the length (in bytes) of the bigint64array from the start of its arraybuffer. ...
...er of arguments. see also array.of(). instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array. this is fixed at construction time and thus read only. bigint64array.prototype.bytelength returns the length (in bytes) of the bigint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. bigint64array.prototype.byteoffset returns the offset (in bytes) of the bigint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. bigint64array.prototype.length returns the number of elements hold in the bigint64array. this is fixed at construction time and thus read only. ...
...And 11 more matches
BigUint64Array - JavaScript
returns the string value of the constructor name. in the case of the biguint64array type this is "biguint64array". static methods biguint64array.from() creates a new biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with a variable number of arguments. see also array.of(). ...
...rray.from() creates a new biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with a variable number of arguments. see also array.of(). instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array. this is fixed at construction time and thus read only. biguint64array.prototype.bytelength returns the length (in bytes) of the biguint64array from the start of its arraybuffer. ...
... arguments. see also array.of(). instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array. this is fixed at construction time and thus read only. biguint64array.prototype.bytelength returns the length (in bytes) of the biguint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. biguint64array.prototype.byteoffset returns the offset (in bytes) of the biguint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. biguint64array.prototype.length returns the number of elements hold in the biguint64array. this is fixed at construction time and thus read only. ...
...And 11 more matches
jspage - Archive of obsolete content
var mootools={version:"1.2.4",build:"0d9113241a90b9cd5643b926795852a2026710d4"};var native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect; var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterimplement||function(){};var d=f||i;h=h!==false;d.constructor=native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.tolowercase();d.prototype.$family={name:e};native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(th...
...b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }return this;};if(c){d.implement(c);}return d;};native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function(){var d=array.prototype.slice.call(arguments); return b.prototype[c].apply(d.shift(),d);};}};native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(...
...nproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){...
...And 10 more matches
ECMAScript 2015 support in Mozilla - Archive of obsolete content
l assembly. it will also appear as the international industry standard iso/iec 16262:2016. a pdf and html version of the standard can be freely downloaded on ecma-international.org. a channel for feedback on ecmascript standards is es-discuss. ...
...e international industry standard iso/iec 16262:2016. a pdf and html version of the standard can be freely downloaded on ecma-international.org. a channel for feedback on ecmascript standards is es-discuss. ...
... standard iso/iec 16262:2016. a pdf and html version of the standard can be freely downloaded on ecma-international.org. a channel for feedback on ecmascript standards is es-discuss. ...
...And 10 more matches
Element.classList - Web APIs
Web › API › Element › classList
(...cls); div.classlist.remove(...cls); // replace class "foo" with class "bar" div.classlist.replace("foo", "bar"); versions of firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods. ...
...ds. see https://bugzilla.mozilla.org/show_bug.cgi?id=814014 polyfill the legacy onpropertychange event can be used to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed. the following polyfill for both classlist and domtokenlist ensures full compliance (coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...sed to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed. the following polyfill for both classlist and domtokenlist ensures full compliance (coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...And 10 more matches
Float32Array - JavaScript
y. float32array.name returns the string value of the constructor name. in the case of the float32array type: "float32array". static methods float32array.from() creates a new float32array from an array-like or iterable object. see also array.from(). float32array.of() creates a new float32array with a variable number of arguments. see also array.of(). instance properties float32array.prototype.buffer returns the arraybuffer referenced by the float32array fixed at construction time and thus read only. float32array.prototype.bytelength returns the length (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.byteoffset returns the offset (in bytes) of the float32array from the start of its arraybuffer. ...
...ay fixed at construction time and thus read only. float32array.prototype.bytelength returns the length (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.byteoffset returns the offset (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.length returns the number of elements hold in the float32array. fixed at construction time and thus read only. instance methods float32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. s...
...ns the number of elements hold in the float32array. fixed at construction time and thus read only. instance methods float32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). float32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Float64Array - JavaScript
y. float64array.name returns the string value of the constructor name. in the case of the float64array type: "float64array". static methods float64array.from() creates a new float64array from an array-like or iterable object. see also array.from(). float64array.of() creates a new float64array with a variable number of arguments. see also array.of(). instance properties float64array.prototype.buffer returns the arraybuffer referenced by the float64array fixed at construction time and thus read only. float64array.prototype.bytelength returns the length (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.byteoffset returns the offset (in bytes) of the float64array from the start of its arraybuffer. ...
...ay fixed at construction time and thus read only. float64array.prototype.bytelength returns the length (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.byteoffset returns the offset (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.length returns the number of elements hold in the float64array. fixed at construction time and thus read only. instance methods float64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float64array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. s...
...ns the number of elements hold in the float64array. fixed at construction time and thus read only. instance methods float64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float64array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). float64array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Int16Array - JavaScript
of an int16array. int16array.name returns the string value of the constructor name. in the case of the int16array type: "int16array". static methods int16array.from() creates a new int16array from an array-like or iterable object. see also array.from(). int16array.of() creates a new int16array with a variable number of arguments. see also array.of(). instance properties int16array.prototype.buffer returns the arraybuffer referenced by the int16array fixed at construction time and thus read only. int16array.prototype.bytelength returns the length (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.byteoffset returns the offset (in bytes) of the int16array from the start of its arraybuffer. fixed at c...
...e int16array fixed at construction time and thus read only. int16array.prototype.bytelength returns the length (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.byteoffset returns the offset (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.length returns the number of elements hold in the int16array. fixed at construction time and thus read only. instance methods int16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int16array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see als...
... returns the number of elements hold in the int16array. fixed at construction time and thus read only. instance methods int16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int16array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int16array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Int32Array - JavaScript
of an int32array. int32array.name returns the string value of the constructor name. in the case of the int32array type: "int32array". static methods int32array.from() creates a new int32array from an array-like or iterable object. see also array.from(). int32array.of() creates a new int32array with a variable number of arguments. see also array.of(). instance properties int32array.prototype.buffer returns the arraybuffer referenced by the int32array fixed at construction time and thus read only. int32array.prototype.bytelength returns the length (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.byteoffset returns the offset (in bytes) of the int32array from the start of its arraybuffer. fixed at c...
...e int32array fixed at construction time and thus read only. int32array.prototype.bytelength returns the length (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.byteoffset returns the offset (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.length returns the number of elements hold in the int32array. fixed at construction time and thus read only. instance methods int32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see als...
... returns the number of elements hold in the int32array. fixed at construction time and thus read only. instance methods int32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Int8Array - JavaScript
the case of an int8array. int8array.name returns the string value of the constructor name. in the case of the int8array type: "int8array". static methods int8array.from() creates a new int8array from an array-like or iterable object. see also array.from(). int8array.of() creates a new int8array with a variable number of arguments. see also array.of(). instance properties int8array.prototype.buffer returns the arraybuffer referenced by the int8array fixed at construction time and thus read only. int8array.prototype.bytelength returns the length (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.byteoffset returns the offset (in bytes) of the int8array from the start of its arraybuffer. fixed at constr...
... by the int8array fixed at construction time and thus read only. int8array.prototype.bytelength returns the length (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.byteoffset returns the offset (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.length returns the number of elements hold in the int8array. fixed at construction time and thus read only. instance methods int8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int8array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also a...
...th returns the number of elements hold in the int8array. fixed at construction time and thus read only. instance methods int8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int8array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Uint16Array - JavaScript
nt16array. uint16array.name returns the string value of the constructor name. in the case of the uint16array type: "uint16array". static methods uint16array.from() creates a new uint16array from an array-like or iterable object. see also array.from(). uint16array.of() creates a new uint16array with a variable number of arguments. see also array.of(). instance properties uint16array.prototype.buffer returns the arraybuffer referenced by the uint16array fixed at construction time and thus read only. uint16array.prototype.bytelength returns the length (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.byteoffset returns the offset (in bytes) of the uint16array from the start of its arraybuffer. fixed...
...16array fixed at construction time and thus read only. uint16array.prototype.bytelength returns the length (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.byteoffset returns the offset (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.length returns the number of elements hold in the uint16array. fixed at construction time and thus read only. instance methods uint16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint16array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see ...
...turns the number of elements hold in the uint16array. fixed at construction time and thus read only. instance methods uint16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint16array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint16array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Uint32Array - JavaScript
nt32array. uint32array.name returns the string value of the constructor name. in the case of the uint32array type: "uint32array". static methods uint32array.from() creates a new uint32array from an array-like or iterable object. see also array.from(). uint32array.of() creates a new uint32array with a variable number of arguments. see also array.of(). instance properties uint32array.prototype.buffer returns the arraybuffer referenced by the uint32array fixed at construction time and thus read only. uint32array.prototype.bytelength returns the length (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.byteoffset returns the offset (in bytes) of the uint32array from the start of its arraybuffer. fixed...
...32array fixed at construction time and thus read only. uint32array.prototype.bytelength returns the length (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.byteoffset returns the offset (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.length returns the number of elements hold in the uint32array. fixed at construction time and thus read only. instance methods uint32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see ...
...turns the number of elements hold in the uint32array. fixed at construction time and thus read only. instance methods uint32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint32array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
Uint8Array - JavaScript
of an uint8array. uint8array.name returns the string value of the constructor name. in the case of the uint8array type: "uint8array". static methods uint8array.from() creates a new uint8array from an array-like or iterable object. see also array.from(). uint8array.of() creates a new uint8array with a variable number of arguments. see also array.of(). instance properties uint8array.prototype.buffer returns the arraybuffer referenced by the uint8array fixed at construction time and thus read only. uint8array.prototype.bytelength returns the length (in bytes) of the uint8array. fixed at construction time and thus read only. uint8array.prototype.byteoffset returns the offset (in bytes) of the uint8array from the start of its arraybuffer. fixed at construction time and thus read onl...
...s the arraybuffer referenced by the uint8array fixed at construction time and thus read only. uint8array.prototype.bytelength returns the length (in bytes) of the uint8array. fixed at construction time and thus read only. uint8array.prototype.byteoffset returns the offset (in bytes) of the uint8array from the start of its arraybuffer. fixed at construction time and thus read only. uint8array.prototype.length returns the number of elements held in the uint8array. fixed at construction time and thus read only. instance methods uint8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint8array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see als...
... returns the number of elements held in the uint8array. fixed at construction time and thus read only. instance methods uint8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint8array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). ...
...And 10 more matches
instanceof - JavaScript
the instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. the return value is a boolean value. 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 object instanceof constructor parameters object the object to test. constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...ub.com/mdn/interactive-examples and send us a pull request. syntax object instanceof constructor parameters object the object to test. constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...e-examples and send us a pull request. syntax object instanceof constructor parameters object the object to test. constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...And 10 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it w...
... } nuint24 = 0; } } return abytes; }; stringview.makefrombase64 = function (sb64inpt, sencoding, nbyteoffset, nlength) { return new stringview(sencoding === "utf-16" || sencoding === "utf-32" ? stringview.base64tobytes(sb64inpt, sencoding === "utf-16" ? 2 : 4).buffer : stringview.base64tobytes(sb64inpt), sencoding, nbyteoffset, nlength); }; /* default values */ stringview.prototype.encoding = "utf-8"; /* default encoding... */ /* instances' methods */ stringview.prototype.makeindex = function (nchrlength, nstartfrom) { var atarget = this.rawdata, nchrend, nrawlength = atarget.length, nstartidx = nstartfrom || 0, nidxend = nstartidx, nstopatchr = isnan(nchrlength) ? infinity : nchrlength; if (nchrlength + 1 > atarget.length) { throw new rangeerror("stringvie...
...ncoding = "utf-8"; /* default encoding... ...
...And 9 more matches
Bytecode Descriptions
rrayliteral creates a new object every time it's evaluated, so this instruction must not be used anywhere it might be executed more than once. there's a shell-only option, newglobal({clonesingletons: true}), that makes this instruction do a deep copy of the object. a few tests use it. format: jof_object objwithproto stack: proto ⇒ obj create and push a new ordinary object with the provided [[prototype]]. this is used to create the .prototype object for derived classes. defining properties initprop operands: (uint32_t nameindex) stack: obj, val ⇒ obj define a data property on an object. obj must be an object. implements: createdatapropertyorthrow as used in propertydefinitionevaluation of regular and shorthand propertydefinitions. format: jof_atom, jof_prop, jof_propinit, jof_ic inithi...
... non-enumerable property. this is used to define class methods. implements: propertydefinitionevaluation for methods, steps 3 and 4, when enumerable is false. format: jof_atom, jof_prop, jof_propinit, jof_ic initlockedprop operands: (uint32_t nameindex) stack: obj, val ⇒ obj like jsop::initprop, but define a non-enumerable, non-writable, non-configurable property. this is used to define the .prototype property on classes. implements: makeconstructor, step 8, when writableprototype is false. format: jof_atom, jof_prop, jof_propinit, jof_ic initelem, inithiddenelem stack: obj, id, val ⇒ obj define a data property on obj with property key id and value val. obj must be an object. implements: createdatapropertyorthrow. this instruction is used for object literals like {0: val} and {[id]: val},...
...eeded like jsop::delelem, but for strict mode code. pushtrue` on success, else throw a typeerror. format: jof_elem, jof_checkstrict hasown stack: id, obj ⇒ (obj.hasownproperty(id)) push true if obj has an own property id. note that obj is the top value, like jsop::in. this opcode is not used for normal js. self-hosted code uses it by calling the intrinsic hasown(id, obj). for example, object.prototype.hasownproperty is implemented this way (see js/src/builtin/object.js). format: jof_ic super superbase stack: callee ⇒ superbase push the superbase of the method callee. the superbase is callee.[[homeobject]].[[getprototypeof]](), the object where super property lookups should begin. callee must be a function that has a homeobject that's an object, typically produced by jsop::callee or jsop...
...And 9 more matches
Debugger.Object - Firefox Developer Tools
debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. the referent’s properties do not appear directly as properties of the debugger.object instance; the debugger can access them only through methods like debugger.object.prototype.getownpropertydescriptor and debugger.object.prototype.defineproperty, ensuring that the debugger will not inadvertently invoke the referent’s getters and setters. spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instanc...
...r.object instance for a given object. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee’s behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remai...
...this accessor may throw if the referent is a scripted proxy or some other sort of exotic object (an opaque wrapper, for example). class a string naming the ecmascript [[class]] of the referent. ...
...And 9 more matches
Debugger.Object - Firefox Developer Tools
debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. the referent's properties do not appear directly as properties of the debugger.object instance; the debugger can access them only through methods like debugger.object.prototype.getownpropertydescriptor and debugger.object.prototype.defineproperty, ensuring that the debugger will not inadvertently invoke the referent's getters and setters. spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance to...
...ger.object instance for a given object. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee's behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remai...
... class a string naming the ecmascript [[class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. ...
...And 9 more matches
Index - Web APIs
Web › API › Index
488 cssunparsedvalue.foreach() api, css typed object model api, cssunparsedvalue, constructor, experimental, houdini, method, needsexample, reference, foreach() the cssunparsedvalue.foreach() method executes a provided function once for each element of the cssunparsedvalue. 489 cssunparsedvalue.keys() api, css typed object model api, cssunparsed...
... 2225 keyboardlayoutmap.foreach() api, experimental, keyboard api, keyboard map, keyboardlayoutmap, method, reference, foreach(), keyboard the foreach() method of the keyboardlayoutmap interface executes a provided function once for each element of the map. 2226 keyboardlayoutmap.get() api, experimental, keyboard api, keyboard map, keyboardlayou...
...s() dom, iterator, method, nodelist, reference, web the nodelist.keys() method returns an iterator allowing to go through all keys contained in this object. the keys are unsigned integer. 2755 nodelist.length api, dom, gecko, needsspectable, nodelist, property, reference the nodelist.length property returns the number of items in a nodelist. 2756 nodelist.prototype.foreach() dom, iterable, method, nodelist, reference, web the foreach() method of the nodelist interface calls the callback given in parameter once for each value pair in the list, in insertion order. 2757 nodelist.values() dom, iterator, method, nodelist, reference, web the nodelist.values() method returns an iterator allowing to go through all values contained in ...
...And 9 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
return false; } } amap.length--; return true; } function typewrite () { if (spart.length === 0 && scroll(asheets[nidx], 0, true) && nidx++ === asheets.length - 1) { clean(); return; } ocurrent.nodevalue += spart.charat(0); spart = spart.slice(1); } function sheet (onode) { this.ref = onode; if (!onode.haschildnodes()) { return; } this.parts = array.prototype.slice.call(onode.childnodes); for (var nchild = 0; nchild < this.parts.length; nchild++) { onode.removechild(this.parts[nchild]); this.parts[nchild] = new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (bt...
...var timeoutid = window.settimeout(code, delay); |*| var intervalid = window.setinterval(func, delay[, arg1, arg2, ...]); |*| var intervalid = window.setinterval(code, delay); |*| \*/ if (document.all && !window.settimeout.ispolyfill) { var __nativest__ = window.settimeout; window.settimeout = function (vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. */) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ? function () { vcallback.apply(null, aargs); } : vcallback, ndelay); }; window.settimeout.ispolyfill = true; } if (document.all && !window.setinterval.ispolyfill) { var __nativesi__ = window.setinterval; window.setinterval = function (vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. */)...
...; return __nativest__(vcallback instanceof function ? function () { vcallback.apply(null, aargs); } : vcallback, ndelay); }; window.settimeout.ispolyfill = true; } if (document.all && !window.setinterval.ispolyfill) { var __nativesi__ = window.setinterval; window.setinterval = function (vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. */) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ? function () { vcallback.apply(null, aargs); } : vcallback, ndelay); }; window.setinterval.ispolyfill = true; } another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. example: var intervalid = setinterval(function() { myfunc('one', '...
...And 9 more matches
TypeError: "x" is not a function - JavaScript
function name? maybe the object you are calling the method on does not have this function? for example, javascript objects have no map function, but the javascript array object does. there are many built-in functions in need of a (callback) function. ...
... object you are calling the method on does not have this function? for example, javascript objects have no map function, but the javascript array object does. there are many built-in functions in need of a (callback) function. ...
...the method on does not have this function? for example, javascript objects have no map function, but the javascript array object does. there are many built-in functions in need of a (callback) function. ...
...And 9 more matches
Old Proxy API - Archive of obsolete content
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. warning: the spidermonkey proxy implementation is a prototype and the proxy api and semantics specifications are unstable. the spidermonkey implementation may not reflect the latest specification draft. it is subject to change anytime. it is provided as an experimental feature. do not rely on it for production code. introduction proxies are objects for which the programmer has to define the semantics in javascript. the default object semantics are implemented in the javascript engine, often written...
.... proxies can be either be trapping or fixed. proxy api catch-alls can be defined only on distinct proxy objects, controlled by a handler object. there are two kinds of proxies: object proxies var proxy = proxy.create(handler, proto); and function proxies : var proxy = proxy.createfunction(handler, calltrap, constructtrap); where: proto is an optional object representing the proxy’s prototype (defaults to null if none is provided). calltrap is a variable-argument function(args) { return any; } that reifies “proxy(args)”. note: the this-binding of the calltrap function is the this-binding of the call-site. constructtrap is an optional variable-argument function(args) { return any-object; } that reifies “new proxy(args)”. the this-binding of the constructtrap is either undefin...
...all-site. constructtrap is an optional variable-argument function(args) { return any-object; } that reifies “new proxy(args)”. the this-binding of the constructtrap is either undefined (in strict mode) or the global object (in non-strict mode). if no constructtrap is provided, performing new proxy(...args) calls the proxy’s calltrap with this bound to a new object delegating to the proxy's prototype. handler is an object that implements the handler api. handler api there are two kinds of traps: fundamental and derived traps. if one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an error is thrown. if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on...
...And 8 more matches
JS_InitClass
syntax jsobject * js_initclass(jscontext *cx, js::handleobject obj, js::handleobject parent_proto, const jsclass *clasp, jsnative constructor, unsigned nargs, const jspropertyspec *ps, const jsfunctionspec *fs, const jspropertyspec *static_ps, const jsfunctionspec *static_fs); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
..."globals" object to use for initializing the class. this must not be null. once js_initclass creates the new class's constructor, it stores the constructor as a property in this object. so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name. parent_proto js::handleobject pointer to an object to be used as a prototype. js_initclass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object. clasp jsclass * pointer to the class structure to initialize. this structure defines the class for use by other api functions. constructor jsnative the constructor for the class. its scope matches that...
...l js_this or js_this_object. instead it must create a new object and return it. nargs unsigned number of arguments for the constructor. ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec, which can be written {0, 0, 0, 0, 0}. these properties, if any, are added to the class's new prototype object. all instances of the new class will inherit these properties via the prototype chain. fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are added to the class's new prototype object. all instances of the new class will inherit these methods via the prototype chain. (this is the...
...And 8 more matches
Xray vision
code. most of the time this is not a problem: the main concern xrays solve is with untrusted web content manipulating objects, and web content is usually working with dom objects. ...
.... so, in gecko 31 and 32 we've added xray support for most javascript built-in objects. ...
... it easy for privileged code to treat untrusted objects like simple dictionaries. any value properties of the object are visible in the xray. if the object has properties which are themselves objects, and these objects are same-origin with the content, then their value properties are visible as well. ...
...And 8 more matches
JXON - Archive of obsolete content
) { oattrib = oxmlparent.attributes.item(nattrlen); this.keyattributes[oattrib.name.tolowercase()] = parsetext(oattrib.value.trim()); } } /* * optional properties... this.keylength = nlength; this.attributeslength = nattrlen; // this.domnode = oxmlparent; */ /* object.freeze(this); */ } /* * optional methods... ...
....keyattributes[oattrib.name.tolowercase()] = parsetext(oattrib.value.trim()); } } /* * optional properties... this.keylength = nlength; this.attributeslength = nattrlen; // this.domnode = oxmlparent; */ /* object.freeze(this); */ } /* * optional methods... ...
... } } /* * optional properties... this.keylength = nlength; this.attributeslength = nattrlen; // this.domnode = oxmlparent; */ /* object.freeze(this); */ } /* * optional methods... ...
...And 7 more matches
Meta programming - JavaScript
s that remain unchanged when implementing custom operations are called invariants. if you violate the invariants of a handler, a typeerror will be thrown. handlers and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. ...
...n implementing custom operations are called invariants. if you violate the invariants of a handler, a typeerror will be thrown. handlers and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. ...
...ons are called invariants. if you violate the invariants of a handler, a typeerror will be thrown. handlers and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. ...
...And 7 more matches
Working with objects - JavaScript
with for...in to iterate over all the enumerable properties of an object. ...
... object.getownpropertynames(o) this method returns an array containing all own properties' names (enumerable or not) of an object o. before ecmascript 5, there was no native way to list all properties of an object. however, this can be achie...
...ould return the following: mycar.make = ford mycar.model = mustang mycar.year = 1969 enumerate the properties of an object starting with ecmascript 5, there are three native ways to list/traverse object properties: for...in loops this method traverses all enumerable properties of an object and its prototype chain. object.keys(o) this method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o. object.getownpropertynames(o) this method returns an array containing all own properties' names (enumerable or not) of an object o. before ecmascript 5, there was no native way to list all properties of an object. however, this can be achieved with the following function: function listallproperties(o) { var objecttoinspect; var ...
...And 7 more matches
Classes - JavaScript
defining classes classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations. class declarations one way to define a class is using a class declaration. to declare a class, you use the class keyword with the name of the class ("rectangle" here). ...
...s of ecmascript. constructor the constructor method is a special method for creating and initializing an object created with a class. there can only be one special method with the name "constructor" in a class. a syntaxerror will be thrown if the class contains more than one occurrence of a constructor method. a constructor can use the super keyword to call the constructor of the super class. prototype methods see also method definitions. class rectangle { constructor(height, width) { this.height = height; this.width = width; } // getter get area() { return this.calcarea(); } // method calcarea() { return this.height * this.width; } } const square = new rectangle(10, 10); console.log(square.area); // 100 static methods the static keyword defines a static me...
... for an application. class point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return math.hypot(dx, dy); } } const p1 = new point(5, 5); const p2 = new point(10, 10); p1.distance; //undefined p2.distance; //undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. this behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode. class animal { ...
...And 7 more matches
DataView - JavaScript
4-byte) parts const left = bigint(dataview.getuint32(byteoffset|0, !!littleendian)>>>0); const right = bigint(dataview.getuint32((byteoffset|0) + 4|0, !!littleendian)>>>0); // combine the two 32-bit values and return return littleendian ? (right<<bigthirtytwo)|left : (left<<bigthirtytwo)|right; } constructor dataview() creates a new dataview object. instance properties dataview.prototype.buffer the arraybuffer referenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. dataview.prototype.byteoffset the offset (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. ins...
...eferenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. dataview.prototype.byteoffset the offset (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. instance methods dataview.prototype.getint8() gets a signed 8-bit integer (byte) at the specified byte offset from the start of the view. dataview.prototype.getuint8() gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the view. ...
...set (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. instance methods dataview.prototype.getint8() gets a signed 8-bit integer (byte) at the specified byte offset from the start of the view. dataview.prototype.getuint8() gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the view. dataview.prototype.getint16() gets a signed 16-bit integer (short) at the specified byte offset from the start of the view. dataview.prototype.getuint16() gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the view. ...
...And 7 more matches
Error - JavaScript
ccurs when a variable or parameter is not of a valid type. urierror creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor error() creates a new error object. static methods error.capturestacktrace() a non-standard v8 function that creates the stack property on an error instance. ...
... of a valid type. urierror creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor error() creates a new error object. static methods error.capturestacktrace() a non-standard v8 function that creates the stack property on an error instance. instance properties error.prototype.message error message. error.prototype.name error name. ...
...s an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor error() creates a new error object. static methods error.capturestacktrace() a non-standard v8 function that creates the stack property on an error instance. instance properties error.prototype.message error message. error.prototype.name error name. error.prototype.description a non-standard microsoft property for the error description. similar to message. error.prototype.number a non-standard microsoft property for an error number. error.prototype.filename a non-standard mozilla property 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. ...
...And 7 more matches
Index - Archive of obsolete content
r, experimental, javascript, method, reference, typedarrays the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state. 2008 date.prototype.tolocaleformat() date, javascript, method, non-standard, prototype, reference the non-standard tolocaleformat() method converts a date to a string using the specified formatting. intl.datetimeformat is an alternative to format dates in a standards-compliant way. see also the newer version of date.prototype.tolocaledatestring(). 2009 ecmascript 2016 to es.next support in mozil...
...vascript, needsupdate no summary! 2010 expression closures function, javascript, language feature, non-standard, obsolete, operator, reference expression closures are a shorthand function syntax for writing simple functions. 2011 function.arity function, javascript, obsolete, property, unimplemented not part of any standard. 2012 function.prototype.isgenerator() function, javascript, method, non-standard, obsolete the non-standard isgenerator() method used to determine whether or not a function is a generator. it has been removed from firefox starting with version 58. 2013 generator comprehensions iterator, javascript, language feature, non-standard, obsolete, reference the generator comprehension syntax was a...
...d removed in browsers. 2066 object.observe() javascript, method, object, obsolete the object.observe() method was used for asynchronously observing the changes to an object. it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. ...
...And 6 more matches
Element.matches() - Web APIs
Web › API › Element › matches
nsole.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
...tcontent + ' is endangered!'); } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
... } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
...And 6 more matches
Border-radius generator - CSS: Cascading Style Sheets
pic) { this.container = document.createelement("div"); this.select = document.createelement("select"); for (var i in units) { var option = document.createelement("option"); option.value = i; option.textcontent = units[i]; this.select.appendchild(option); } this.container.classname = 'dropdown ' + 'unit-' + topic; this.container.appendchild(this.select); } unitselector.prototype.setvalue = function setvalue(value) { this.salect.value = value; } var radiuscontainer = function radiuscontainer(node) { var radius = document.createelement('div'); var handle = document.createelement('div'); var x = node.getattribute('data-x'); var y = node.getattribute('data-y'); var active = false; this.id = node.id; this.node = node; this.radius = radius; this.handle...
...iner.style.display = 'block'; unitr.container.style.display = 'none'; sliderw.style.display = 'block'; sliderh.style.display = 'block'; sliderr.style.display = 'none'; this.setunitx(this.unitx); this.setunity(this.unity); this.updatewidth(); this.updateheight(); } this.updateborderradius(); }.bind(this)); this.updateborderradius(); } radiuscontainer.prototype.updatewidth = function updatewidth() { this.node.style.width = this.width + units[this.unitx]; var value = math.round(this.width / 2); inputslidermanager.setvalue(this.topic + '-w', value, false); } radiuscontainer.prototype.updateheight = function updateheight() { this.node.style.height = this.height + units[this.unity]; var value = math.round(this.height / 2); inputslidermanager.
...= this.width + units[this.unitx]; var value = math.round(this.width / 2); inputslidermanager.setvalue(this.topic + '-w', value, false); } radiuscontainer.prototype.updateheight = function updateheight() { this.node.style.height = this.height + units[this.unity]; var value = math.round(this.height / 2); inputslidermanager.setvalue(this.topic + '-h', value, false); } radiuscontainer.prototype.updateradius = function updateradius() { var value = math.round(this.size / 2); this.node.style.width = this.size + units[this.unitr]; this.node.style.height = this.size + units[this.unitr]; inputslidermanager.setvalue(this.topic, value, false); } radiuscontainer.prototype.setwidth = function setwidth(value) { this.radius.style.display = 'block'; this.width = 2 * value; this.node...
...And 6 more matches
JavaScript Client API - Archive of obsolete content
xt. cleartext must be a json-able object. put into it all values that you want to have encrypted, stored on the server, decrypted, and synced up. you may find it useful to write getters and setters for various properties of your record implementation. ...
... put into it all values that you want to have encrypted, stored on the server, decrypted, and synced up. you may find it useful to write getters and setters for various properties of your record implementation. ...
... the store must also make updates to the underl...
...And 5 more matches
Archived JavaScript Reference - Archive of obsolete content
browsers. you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. ...
...tended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state.date.prototype.tolocaleformat()the non-standard tolocaleformat() method converts a date to a string using the specified formatting. intl.datetimeformat is an alternative to format dates in a standards-compliant way. ...
...it has been removed from firefox starting with version 58.generator comprehensionsthe generator comprehension syntax was a javascript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. ...
...And 5 more matches
NSS functions
reference documents the functions most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions nss_getclientauthdata mxr 3.2 and later nss_setdomesticpolicy mxr 3.2 and later nss_setexportpolicy mxr 3.2 and later nss_setfrancepolicy mxr 3.2 and l...
...n replaced with newer versions. the deprecated functions are not supported by the new ssl shared libraries. applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below. each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. function name/documentation source code replacement in nss 3.2 ssl_enable mxr ssl_optionset ssl_enablecipher mxr ssl_cipherprefsetdefault ssl_enabledefault mxr ssl_optionsetdefault ssl_redohandshake mxr ssl_rehandshake ...
...r ssl_cipherpolicyset certificate functions the public functions listed here are used to interact with certificate databases. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions cert_addcerttolisttail mxr 3.2 and later cert_addextension mxr 3.5 and later cert_addocspacceptableresponses mxr 3.6 and later cert_addokdomainname mxr 3.
...And 5 more matches
EventTarget.addEventListener() - Web APIs
ndard rules. this is shown in the following example: <script> function logid() { console.log(this.id); } </script> <table id="my_table" onclick="logid();"><!-- when called, `this` will refer to the global object --> ... </table> the value of this within logid() is a reference to the global object window (or undefined in the case of strict mode. specifying "this" using bind() the function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. this lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. note, however, that you'll need to keep a reference to the listener around so you can remove it later. this is an example with and without bind(): const som...
...ta, much less to get any data back from them after they execute. event listeners only take one argument, the event object, which is automatically passed to the listener, and the return value is ignored. so how can we get data in and back out of them again? there are a number of good methods for doing this. getting data into an event listener using "this" as mentioned above, you can use function.prototype.bind() to pass a value to an event listener via the this reference variable. const mybutton = document.getelementbyid('my-button-id'); const somestring = 'data'; mybutton.addeventlistener('click', function () { console.log(this); // expected value: 'data' }.bind(somestring)); this method is suitable when you don't need to know which html element the event listener fired on programmatically...
...internet explorer 8 by using the following code at the beginning of your script. the code supports the use of handleevent() and also the domcontentloaded event. note: usecapture is not supported, as ie 8 does not have any alternative method. the following code only adds ie 8 support. this ie 8 polyfill only works in standards mode: a doctype declaration is required. ...
...And 5 more matches
RegExp - JavaScript
e value. (perl is the programming language from which javascript modeled its regular expressions.). see also deprecated regexp properties. constructor regexp() creates a new regexp object. static properties get regexp[@@species] the constructor function that is used to create derived objects. regexp.lastindex the index at which to start the next match. ...
...ular expressions.). see also deprecated regexp properties. constructor regexp() creates a new regexp object. static properties get regexp[@@species] the constructor function that is used to create derived objects. regexp.lastindex the index at which to start the next match. instance properties regexp.prototype.flags a string that contains the flags of the regexp object. regexp.prototype.dotall whether . matches newlines or not. ...
...onstructor regexp() creates a new regexp object. static properties get regexp[@@species] the constructor function that is used to create derived objects. regexp.lastindex the index at which to start the next match. instance properties regexp.prototype.flags a string that contains the flags of the regexp object. regexp.prototype.dotall whether . matches newlines or not. regexp.prototype.global whether to test the regular expression against all possible matches in a string, or only against the first. ...
...And 5 more matches
New in JavaScript 1.2 - Archive of obsolete content
. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
...vascript1.2"> <!-- javascript for navigator 4.0. --> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
...ipt for navigator 4.0. --> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
...And 4 more matches
Log.jsm
to a minimum. config information regarding important configuration options the system is using that affect how it runs. debug detailed information on the flow through the system. expect these to be written to logs only. trace most detailed information. expect these to be written to logs only. ...
... through the system. expect these to be written to logs only. trace most detailed information. expect these to be written to logs only. ...
... written to logs only. ...
...And 4 more matches
SourceMap.jsm
lowing. sources: an array of urls to the original source files. names: an array of identifiers that can be referenced by individual mappings. sourceroot: optional. the url root from which all sources are relative. mappings: a string of base64 vlqs which contain the actual mappings. file: the generated filename this source map is associated with. sourcemapconsumer.prototype.originalpositionfor(generatedposition) returns the original source, line, and column information for the generated source's line and column positions provided. the only argument is an object with the following properties: line: the line number in the generated source. column: the column number in the generated source. and an object is returned with the following properties: ...
...ance of the sourcemapgenerator represents a source map which is being built incrementally. new sourcemapgenerator(startofsourcemap) to create a new one, you must pass an object with the following properties: file: the filename of the generated source that this source map is associated with. sourceroot: an optional root for all relative urls in this source map. sourcemapgenerator.prototype.addmapping(mapping) add a single mapping from original source line and column to the generated source's line and column 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 (re...
...nd column 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 ...
...And 4 more matches
Enumerability and ownership of properties - JavaScript
le flag is set to true, which is the default for properties created via simple assignment or via a property initializer (properties defined via object.defineproperty and such default enumerable to false). enumerable properties show up in for...in loops unless the property's key is a symbol. ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain. properties of an object can also be retrieved in total. there are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. property enumerability and ownership - built-in methods of detection, retrieval, and iterati...
...l. there are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. ...
...er of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. ...
...And 4 more matches
TypeError: Reduce of empty array with no initial value - JavaScript
these functions optionally take an initialvalue (which will be used as the first argument to the first call of the callback). ...
... these functions optionally take an initialvalue (which will be used as the first argument to the first call of the callback). ...
... these functions optionally take an initialvalue (which will be used as the first argument to the first call of the callback). ...
...And 4 more matches
Map - JavaScript
thing is stored at a key. for this reason (and because there were no built-in alternatives), objects have been used as maps historically. however, there are important differences that make map preferable in certain cases: map object accidental keys a map does not contain any keys by default. it only contains what is explicitly put into it. an object has a prototype, so it contains default keys that could collide with your own keys if you're not careful. note: as of es5, this can be bypassed by using object.create(null), but this is seldom done. key types a map's keys can be any value (including functions, objects, or any primitive). the keys of an object must be either a string or a symbol. key order the ke...
...-4321", address: "321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object. static properties get map[@@species] the constructor function that is used to create derived objects. ...
... 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object. static properties get map[@@species] the constructor function that is used to create derived objects. instance properties map.prototype.size returns the number of key/value pairs in the map object. instance methods map.prototype.clear() removes all key-value pairs from the map object. ...
...And 4 more matches
Object initializer - JavaScript
3 let param = 'size' let config = { [param]: 12, ['mobile' + param.charat(0).touppercase() + param.slice(1)]: 4 } console.log(config) // {size: 12, mobilesize: 4} spread properties the rest/spread properties for ecmascript proposal (stage 4) adds spread properties to object literals. it copies own enumerable properties from a provided object onto a new object. ...
...cloning (excluding prototype) or merging objects is now possible using a shorter syntax than object.assign(). let obj1 = { foo: 'bar', x: 42 } let obj2 = { foo: 'baz', y: 13 } let clonedobj = { ...obj1 } // object { foo: "bar", x: 42 } let mergedobj = { ...obj1, ...obj2 } // object { foo: "baz", x: 42, y: 13 } note that object.assign() triggers setters, whereas the spread operator doesn't! ...
...{ foo: "bar", x: 42 } let mergedobj = { ...obj1, ...obj2 } // object { foo: "baz", x: 42, y: 13 } note that object.assign() triggers setters, whereas the spread operator doesn't! ...
...And 4 more matches
Reference - Archive of obsolete content
its constructor note : the function.constructor seems to keep on refering to itself, if you do the following you get same results which suggests that this is indeed the top level object. alert(function.constructor.constructor) alert(function.constructor.constructor.constructor.constructor) function == object however the following statement suggests that function is object. ...
...efering to itself, if you do the following you get same results which suggests that this is indeed the top level object. alert(function.constructor.constructor) alert(function.constructor.constructor.constructor.constructor) function == object however the following statement suggests that function is object. ...
....constructor.constructor.constructor) function == object however the following statement suggests that function is object. but when we create a prototype method for object its also available in function object.prototype.myfunction = function() {}; alert(object.myfunction); //available in object alert(function.myfunction); //available in function also the opposite is correct, when we create a prototype method for function it is available in object function.prototype.myfunction = function() {}; alert(object.myfunction); //available in object alert(function.myfunction); //available in function so no matter what we prototype function or object , it will be available in both... <p>so all this now suggests that function is object. note that instances derived from function/object also have this f...
...And 3 more matches
Mozilla DOM Hacking Guide
p me! static prbool sdosecuritycheckinaddproperty;: help me! nsdomclassinfo::init() this method is to be called only once. its purpose is, well, to initialize... it does a lot of different things: fill the blanks in the sclassinfodata array, initialize the sxpconnect and ssecman data members, create a new javascript context, define the jsstring data members, and register class names and class prototypes. finally it sets sisinitialized to true. the actions that concern the dom are described below. first, the call to callgetservice() initializes sxpconnect. then the script security manager (ssecman) is initialized. getsafejscontext() grabs us a cool js context to run our javascript code in. the part about componentregistrar is designed to allow external modules (in this case xpath) to be include...
...interface, yet you want the xmlhttprequest object to be available from javascript. #define dom_classinfo_map_begin_no_class_if(_class, _interface) _dom_classinfo_map_begin(_class, &ns_get_iid(_interface), pr_false) this macro should be used for dom classes that have no "leaf" interface. for example, there is no htmlspanelement in the w3c dom specification. therefore, the first interface in the prototype chain for the span element is htmlelement. however we do want to be able to access htmlspanelement to modify it. this macro allows you to do that. see bug 92071 for more information. let's now see how to specify the interfaces available from javascript for a particular dom class. #define dom_classinfo_map_entry(_if) &ns_get_iid(_if), the array of pointers interface_list is filled with the addr...
... now possible. i will try to update this guide as soon as possible. please send any comment to fabian guisset. ...
...And 3 more matches
JS_NewObject
must not have the jsclass_global_flags bits set (use js_newglobalobject instead). if clasp is non-null, the caller must ensure that the jsclass remains alive throughout the lifetime of the new object, including the garbage collection cycle that finally frees it. the usual way to do this is to make jsclasses global or static. proto js::handle&lt;jsobject*&gt; pointer to the prototype object to use for the new object. the new object will inherit all of the prototype object's properties and methods, and the new object's __proto__ property will be a reference to the prototype object. js_newobject: if this is null, a default prototype object is used. obsolete since jsapi 38 js_newobject now always uses a default prototype object. js_newobjectwithgivenproto: if this...
... parent js::handle&lt;jsobject*&gt; pointer to the parent of the new object. the new object's __parent__ property will be a reference to this object. if parent is null, a default parent object is used. ...
...a reference to this object. if parent is null, a default parent object is used. obsolete since jsapi 39 description js_newobject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to establish the new object. clasp is a pointer to an existing class to use for internal methods, such as finalize. the javascript engine selects a prototype object for you. on success, js_newobject returns a pointer to the new object. otherwise it returns null. added in spidermonkey 1.8 js_newobjectwithgivenproto creates a new object with the specified prototype. if null is passed as proto, the new object will have a prototype with the js value of null. to create a new object as a property of an existing object, use js_defineobject, a convenience ...
...And 3 more matches
nsIXPConnect
obsolete since gecko 2.0 jsval getxowforobject(in jscontextptr ajscontext, in jsobjectptr aparent, in jsobjectptr awrap...
...sholder(in voidptr aholder); native code only! void reparentscopeawarewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectptr anewscope); obsolete since gecko 1.9.1 nsixpconnectjsobjectholder reparentwrappednativeiffound(in jscontextptr ajscontext, in jsobjectptr ascope, in jsobjectptr anewparent, in nsisupports acomobj); void restorewrappednativeprototype(in jscontextptr ajscontext, in jsobjectptr ascope, in nsiclassinfo aclassinfo, in nsixpconnectjsobjectholder aprototype); void setdebugmodewhenpossible(in prbool mode); native code only! void setdefaultsecuritymanager(in nsixpcsecuritymanager amanager, in pruint16 flags); nsixpcfunctionthistranslator setfunctionthistranslator(in nsiidref aiid, in nsixpcfunctionthistra...
...ssing exception missing description definedomquickstubs() define quick stubs on the given object, @a proto. [noscript,notxpcom] prbool definedomquickstubs( in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray ); parameters cx a context. requires request. proto the (newly created) prototype object for a dom class. the js half of an xpcwrappednativeproto. flags property flags for the quick stub properties--should be either jsprop_enumerate or 0. interfacecount the number of interfaces the class implements. interfacearray the interfaces the class implements; interfacearray and interfacecount are like what nsiclassinfo.getinterfaces returns. return value missing description e...
...And 3 more matches
WebIDL bindings
ng a typeerror, you should use errorresult::throwtypeerror() instead of calling throw(). custom extended attributes our webidl parser and code generator recognize several extended attributes that are not present in the webidl spec. [alias=propname] this extended attribute can be specified on a method and indicates that another property with the specified name will also appear on the interface prototype object and will have the same function object value as the property for the method. for example: interface myinterface { [alias=performsomething] void dosomething(); }; myinterface.prototype.performsomething will have the same function object value as myinterface.prototype.dosomething. multiple [alias] extended attribute can be used on the one method. [alias] cannot be used on a static meth...
... cannot be used on a static method, nor on methods on a global interface (such as window). aside from regular property names, the name of an alias can be symbol.iterator. this is specified by writing [alias="@@iterator"]. [bindingalias=propname] this extended attribute can be specified on an attribute and indicates that another property with the specified name will also appear on the interface prototype object and will call the same underlying c++ implementation for the getter and setter. this is more efficient than using the same binaryname for both attributes, because it shares the binding glue code between them. the properties still have separate getter/setter functions in javascript, so from the point of view of web consumers it's as if you actually had two separate attribute declarations on...
...inaryname for both attributes, because it shares the binding glue code between them. the properties still have separate getter/setter functions in javascript, so from the point of view of web consumers it's as if you actually had two separate attribute declarations on your interface. for example: interface myinterface { [bindingalias=otherattr] readonly attribute boolean attr; }; myinterface.prototype.otherattr and myinterface.prototype.attr will both exist, have separate getter/setter functions, but call the same binding glue code and implementation function on the objects implementing myinterface. multiple [bindingalias] extended attributes can be used on a single attribute. [chromeonly] this extended attribute can be specified on any method, attribute, or constant on an interface or on a...
...And 3 more matches
Debugger.Frame - Firefox Developer Tools
ethods it triggers. even though the debuggee and debugger share the same javascript stack, frames pushed for spidermonkey’s calls to handler methods to report events in the debuggee are never considered visible frames.) invocation functions and “debugger” frames aninvocation function is any function in this interface that allows the debugger to invoke code in the debuggee: debugger.object.prototype.call, debugger.frame.prototype.eval, and so on. while invocation functions differ in the code to be run and how to pass values to it, they all follow this general procedure: letolder be the youngest visible frame on the stack, or null if there is no such frame. (this is never one of the the debugger’s own frames; those never appear as debugger.frame instances.) push a "debugger" fram...
...t visible frame on the stack, or null if there is no such frame. (this is never one of the the debugger’s own frames; those never appear as debugger.frame instances.) push a "debugger" frame on the stack, witholder as its older property. invoke the debuggee code as appropriate for the given invocation function, with the "debugger" frame as its continuation. for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame. when the debuggee code completes, whether by returning, throwing an exception or being terminated, pop the "debugger" frame, and return an appropriate completion value from the invocation function to the debugger. when a debugger calls an invocation function to run debuggee code, t...
...ate completion value from the invocation function to the debugger. when a debugger calls an invocation function to run debuggee code, that code’s continuation is the debugger, not the next debuggee code frame. pushing a "debugger" frame makes this continuation explicit, and makes it easier to find the extent of the stack created for the invocation. accessor properties of the debugger.frame prototype object a debugger.frame instance inherits the following accessor properties from its prototype: type a string describing what sort of frame this is: "call": a frame running a function call. (we may not be able to obtain frames for calls to host functions.) "eval": a frame running code passed to eval. "global": a frame running global code (javascript that is neither ...
...And 3 more matches
ChildNode.after() - Web APIs
Web › API › ChildNode › after
r with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? argitem : document.createtextnode(string(argitem))); }); this.parentnode.insertbefore(docfrag, this.nextsibling); } }); }); })([element.prototype, characterdata...
...slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? ...
... docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? ...
...And 3 more matches
TextEncoder - Web APIs
mentation to support non-utf-8 text encodings on github. example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. ...
...') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method. polyfill the below polyfi...
...l might be impractical for large strings. finally, note that you should run the below code through a minifier (especially closure compiler) to turn sequences like 0x1e << 3 into 0xf0. these sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. if (typeof textencoder === "undefined") { textencoder=function textencoder(){}; textencoder.prototype.encode = function encode(str) { "use strict"; var len = str.length, respos = -1; // the uint8array's length must be at least 3x the length of the string because an invalid utf-16 // takes up the equivelent space of 3 utf-8 characters to encode it properly. however, array's // have an auto expanding length and 1.5x should be just the right balance for most...
...And 3 more matches
WebGL model view projection - Web APIs
and uniform locations this.positionlocation = gl.getattriblocation(this.webglprogram, 'position'); this.colorlocation = gl.getuniformlocation(this.webglprogram, 'color'); // tell webgl to test the depth when drawing, so if a square is behind // another square it won't be drawn gl.enable(gl.depth_test); } webglbox draw now we'll create a method to draw a box on the screen. webglbox.prototype.draw = function(settings) { // create some attribute data; these are the triangles that will end being // drawn to the screen. there are two that form a square. var data = new float32array([ //triangle 1 settings.left, settings.bottom, settings.depth, settings.right, settings.bottom, settings.depth, settings.left, settings.top, settings.depth, //triangle 2 se...
...e shrunk down in order to not fill the entirety of clip space. this matrix is sent directly to the shader, having been multiplied in javascript beforehand. the following code sample defines a method on the cubedemo object that will create the model matrix. it uses custom functions to create and multiply matrices as defined in the mdn webgl shared code. ...
...efactor) then factoring out the scalefactor, we get this: w = (4 + 1) * scalefactor which is exactly the same as the (z + 1) * scalefactor that we used in the previous example. in the box demo, an additional computesimpleprojectionmatrix() method is added. this is called in the draw() method and has the scale factor passed to it. the result should be identical to the last example: cubedemo.prototype.computesimpleprojectionmatrix = function(scalefactor) { this.transforms.projection = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, scalefactor, 0, 0, 0, scalefactor ]; }; although the result is identical, the important step here is in the vertex shader. rather than modifying the vertex directly, it gets multiplied by an additional projection matrix, which (as the name suggests) projects 3d point...
...And 3 more matches
Using Web Workers - Web APIs
nctions takes at least one argument, the method name we want to query. then we can pass in the arguments that the method needs. */ this.sendquery = function() { if (arguments.length < 1) { throw new typeerror('queryableworker.sendquery takes at least one argument'); return; } worker.postmessage({ 'querymethod': arguments[0], 'queryarguments': array.prototype.slice.call(arguments, 1) }); } we finish queryableworker with the onmessage method. if the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.: worker.onmessage = function(event) { if (event.data instanceof object && event.data.hasownproperty('querymethodlistene...
...printstuff', a - b); }, waitsometime: function() { settimeout(function() { reply('doalert', 3, 'seconds'); }, 3000); } } function reply() { if (arguments.length < 1) { throw new typeerror('reply - takes at least one argument'); return; } postmessage({ querymethodlistener: arguments[0], querymethodarguments: array.prototype.slice.call(arguments, 1) }); } /* this method is called when main page calls queryworker's postmessage method directly*/ function defaultreply(message) { // do something } and the onmessage method is now trivial: onmessage = function(event) { if (event.data instanceof object && event.data.hasownproperty('querymethod') && event.data.hasownproperty('querymethodargume...
... page): <!doctype html> <html> <head> <meta charset="utf-8" /> <title>mdn example - queryable worker</title> <script type="text/javascript"> /* queryableworker instances methods: * sendquery(queryable function name, argument to pass 1, argument to pass 2, etc. ...
...And 3 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
ay[, arg1, arg2, ...]); |*| var intervalid = window.setinterval(code, delay); |*| \*/ (function() { settimeout(function(arg1) { if (arg1 === 'test') { // feature test is passed, no need for polyfill return; } var __nativest__ = window.settimeout; window.settimeout = function(vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. ...
... } : vcallback, ndelay); }; }, 0, 'test'); var interval = setinterval(function(arg1) { clearinterval(interval); if (arg1 === 'test') { // feature test is passed, no need for polyfill return; } var __nativesi__ = window.setinterval; window.setinterval = function(vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. ...
...ettimeout, then when it's called, its this is not set so it defaults to the window object. there's also no option to pass a thisarg to settimeout as there is in array methods like foreach, reduce, etc. and as shown below, using call to set this doesn't work either. ...
...And 3 more matches
RangeError: precision is out of range - JavaScript
f range (edge) rangeerror: precision {0} out of range (firefox) rangeerror: toexponential() argument must be between 0 and 20 (chrome) rangeerror: tofixed() digits argument must be between 0 and 20 (chrome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
...on {0} out of range (firefox) rangeerror: toexponential() argument must be between 0 and 20 (chrome) rangeerror: tofixed() digits argument must be between 0 and 20 (chrome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
...) rangeerror: toexponential() argument must be between 0 and 20 (chrome) rangeerror: tofixed() digits argument must be between 0 and 20 (chrome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
...And 3 more matches
Intl.Locale - JavaScript
and numbering system type. traditionally, the intl api used strings to represent locales, just as unicode does. this is a simple and lightweight solution that works well. adding a locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. constructor intl.locale() creates a new locale object. ...
...tweight solution that works well. adding a locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. constructor intl.locale() creates a new locale object. instance properties intl.locale.prototype.basename returns basic, core information about the locale in the form of a substring of the complete data string. intl.locale.prototype.calendar returns the part of the locale that indicates the locale's calendar era. ...
...e language, script, and region, as well as extension tags. constructor intl.locale() creates a new locale object. instance properties intl.locale.prototype.basename returns basic, core information about the locale in the form of a substring of the complete data string. intl.locale.prototype.calendar returns the part of the locale that indicates the locale's calendar era. intl.locale.prototype.casefirst returns whether case is taken into account for the locale's collation rules. intl.locale.prototype.collation returns the collation type for the locale, which is used to order strings according to the locale's rules. ...
...And 3 more matches
Object.defineProperty() - JavaScript
descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. bear in mind that these attributes are not necessarily the descriptor's own properties. inherited properties will be considered as well. in order to ensure these defaults are preserved, you might freeze the object.prototype upfront, specify all options explicitly, or point to null with object.create(null). // using __proto__ var obj = {}; var descriptor = object.create(null); // no inherited properties descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults object.defineproperty(obj, 'key', descriptor); // being explicit object.defineproperty(obj, 'key', { enumerable: false, ...
... d = withvalue.d || ( withvalue.d = { enumerable: false, writable: false, configurable: false, value: value } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // ... and ... object.defineproperty(obj, 'key', withvalue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (object.freeze || object)(object.prototype); examples if you want to see how to use the object.defineproperty method with a binary-flags-like syntax, see additional examples. creating a property when the property specified doesn't exist in the object, object.defineproperty() creates a new property as described. fields may be...
...e assigned console.log(instance.myname); // this is my name string inheritance of properties if an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. if these methods use a variable to store the value, this value will be shared by all objects. ...
...And 3 more matches
Comparing Reflect and Object methods - JavaScript
bject. returns undefined if it does not exist, and a typeerror if anything other than an object (a primitive) is passed in as the first argument. getownpropertydescriptors() object.getownpropertydescriptors() returns an object containing a property descriptor of each passed-in object. returns an empty object if the passed-in object has no owned property descriptors. ...
... it does not exist, and a typeerror if anything other than an object (a primitive) is passed in as the first argument. getownpropertydescriptors() object.getownpropertydescriptors() returns an object containing a property descriptor of each passed-in object. returns an empty object if the passed-in object has no owned property descriptors. ...
...typeerror if anything other than an object (a primitive) is passed in as the first argument. getownpropertydescriptors() object.getownpropertydescriptors() returns an object containing a property descriptor of each passed-in object. returns an empty object if the passed-in object has no owned property descriptors. n/a getprototypeof() object.getprototypeof() returns the prototype of the given object. ...
...And 3 more matches
Set - JavaScript
equality for -0 and 0" in the browser compatibility table for details. nan and undefined can also be stored in a set. all nan values are equated (i.e. nan is considered the same as nan, even though nan !== nan). constructor set() creates a new set object. static properties get set[@@species] the constructor function that is used to create derived objects. ...
... can also be stored in a set. all nan values are equated (i.e. nan is considered the same as nan, even though nan !== nan). constructor set() creates a new set object. static properties get set[@@species] the constructor function that is used to create derived objects. instance properties set.prototype.size returns the number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. returns the set object. ...
... same as nan, even though nan !== nan). constructor set() creates a new set object. static properties get set[@@species] the constructor function that is used to create derived objects. instance properties set.prototype.size returns the number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. returns the set object. set.prototype.clear() removes all elements from the set object. set.prototype.delete(value) removes the element associated to the value and returns the value that set.prototype.has(value) would have previously returned. set.prototype.has(value) will return false afterwards. set.prototype.has(value) returns a boolean asserting whether an element is present with the given value in the set object or not. i...
...And 3 more matches
Symbol - JavaScript
ax "new symbol()". static properties symbol.asynciterator a method that returns the default asynciterator for an object. used by for await...of. symbol.hasinstance a method determining if a constructor object recognizes an object as its instance. used by instanceof. symbol.isconcatspreadable a boolean value indicating if an object should be flattened to its array elements. used by array.prototype.concat(). symbol.iterator a method returning the default iterator for an object. used by for...of. symbol.match a method that matches against a string, also used to determine if an object may be used as a regular expression. used by string.prototype.match(). symbol.matchall a method that returns an iterator, that yields matches of the regular expression against a string. used by string.prot...
...mbol.match a method that matches against a string, also used to determine if an object may be used as a regular expression. used by string.prototype.match(). symbol.matchall a method that returns an iterator, that yields matches of the regular expression against a string. used by string.prototype.matchall(). symbol.replace a method that replaces matched substrings of a string. used by string.prototype.replace(). symbol.search a method 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 o...
... 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 created in the global symbol registry with key. ...
...And 3 more matches
Spread syntax (...) - JavaScript
et objclone = { ...obj }; rest syntax (parameters) rest syntax looks exactly like spread syntax. in a way, rest syntax is the opposite of spread syntax. spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. see rest parameters. examples spread in function calls replace apply() it is common to use function.prototype.apply() in cases where you want to use the elements of an array as arguments to a function. function myfunction(x, y, z) { } const args = [0, 1, 2]; myfunction.apply(null, args); with spread syntax the above can be written as: function myfunction(x, y, z) { } const args = [0, 1, 2]; myfunction(...args); any argument in the argument list can use spread syntax, and the spread syntax can be used...
...sily used with new thanks to spread syntax: const datefields = [1970, 0, 1]; // 1 jan 1970 const d = new date(...datefields); to use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application: function applyandnew(constructor, args) { function partial () { return constructor.apply(this, args); }; if (typeof constructor.prototype === "object") { partial.prototype = object.create(constructor.prototype); } return partial; } function myconstructor () { console.log("arguments.length: " + arguments.length); console.log(arguments); this.prop1="val1"; this.prop2="val2"; }; const myarguments = ["hi", "how", "are", "you", "mr", null]; const myconstructorwitharguments = applyandnew(myconstructor, myargume...
...fectively goes one level deep while copying an array. therefore, it may be unsuitable for copying multidimensional arrays, as the following example shows. (the same is true with object.assign() and spread syntax.) const a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // oh no! now array 'a' is affected as well: a // [[], [2], [3]] a better way to concatenate arrays array.prototype.concat() is often used to concatenate an array to the end of an existing array. without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // append all items from arr2 onto arr1 arr1 = arr1.concat(arr2); with spread syntax this becomes: let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] // note: not to use ...
...And 3 more matches
Using the WebAssembly JavaScript API - WebAssembly
irst word of linear memory, you can do this: new uint32array(memory.buffer)[0] = 42; you can then return the same value using: new uint32array(memory.buffer)[0] try this now in your demo — save what you’ve added so far, load it in your browser, then try entering the above two lines in your javascript console. growing memory a memory instance can be grown by calls to memory.prototype.grow(), where again the argument is specified in units of webassembly pages: memory.grow(1); if a maximum value was supplied upon creation of the memory instance, attempts to grow past this maximum will throw a webassembly.rangeerror exception. the engine takes advantage of this supplied upper-bounds to reserve memory ahead of time, which can make resizing more efficient. note: since an arrayb...
...bassembly pages: memory.grow(1); if a maximum value was supplied upon creation of the memory instance, attempts to grow past this maximum will throw a webassembly.rangeerror exception. the engine takes advantage of this supplied upper-bounds to reserve memory ahead of time, which can make resizing more efficient. note: since an arraybuffer’s bytelength is immutable, after a successful memory.prototype.grow() operation the buffer getter will return a new arraybuffer object (with the new bytelength) and any previous arraybuffer objects become “detached”, or disconnected from the underlying memory they previously pointed to. just like functions, linear memories can be defined inside a module or imported. similarly, a module may also optionally export its memory. this means that javascript ca...
... from the underlying memory they previously pointed to. just like functions, linear memories can be defined inside a module or imported. similarly, a module may also optionally export its memory. this means that javascript can get access to the memory of a webassembly instance either by creating a new webassembly.memory and passing it in as an import or by receiving a memory export (via instance.prototype.exports). more involved memory example let’s make the above assertions clearer by looking at a more involved memory example — a webassembly module that imports the memory instance we defined earlier, populates it with an array of integers, then sums them. you can find this at memory.wasm. make a local copy of memory.wasm in the same directory as before. note: you can see the mod...
...And 3 more matches
Private Properties - Archive of obsolete content
prefix each private property name with an underscore. consider the following example: function point(x, y) { this._x = x; this._y = y; } the properties _x and _y are intended to be private, and should only be accessed by member functions. to make a private property readable/writable from any function, it's common to define getter/setter functions for the property, respectively: point.prototype.getx = function () { return this._x; }; point.prototype.setx = function (x) { this._x = x; }; point.prototype.gety = function () { return this._y; }; point.prototype.sety = function (y) { this._y = y; }; the above technique is simple and clearly expresses intent. however, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is...
...bles: function point(_x, _y) { this.getx = function () { return _x; }; this.setx = function (x) { _x = x; }; this.gety = function () { return _y; }; this.sety = function (y) { _y = y; }; } note that this technique requires member functions that need access to private properties to be defined on the object itself, instead of its prototype. this is slightly less efficient than using the underscore convention, but not significantly for most applications. the advantage of this technique is that it offers more protection: there is no way for the user to access a private property, except by using its getter or setter function. however, the use of closures makes private properties too restrictive: since there is no way to access variab...
...ingle object, called a namespace, and then store the namespace as a private property on the original object. ...
...And 2 more matches
test/assert - Archive of obsolete content
t, as determined by ===. if the expected value is a date object, the actual value is equivalent if it is also a date object that refers to the same time. other pairs that do not both pass typeof value == "object", equivalence is determined by ==. for all other object pairs, including array objects, equivalence is determined by having the same number of owned properties (as verified with object.prototype.hasownproperty.call), the same set of keys (although not necessarily the same order), equivalent values for every corresponding key, and an identical "prototype" property. note: this accounts for both named and indexed properties on arrays. assert.deepequal({ a: "foo" }, { a: "foo" }, "equivalent objects"); parameters actual : object the actual result. expected : object the expected resul...
... expected : object the expected result. message : string optional message to log, providing extra information about the test. notdeepequal(actual, expected, message) tests that two objects do not have a deep equality relation, using the negation of the test for deep equality: assert.notdeepequal({ a: "foo" }, object.create({ a: "foo" }), "object's inherit from different prototypes"); parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. strictequal(actual, expected, message) tests that two objects are equal, using the strict equality operator ===: // this test will pass, because "==" will perform type conversion exports["test coercive equality"] =...
... the object returned by that function. ...
...And 2 more matches
QuerySelector - Archive of obsolete content
along the lines of other frameworks such as jquery or prototype, shortening the "queryselector" name can be convenient: function $ (selector, el) { if (!el) {el = document;} return el.queryselector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.queryselectorall(selector); // note: the returned object is a nodelist. ...
...the "queryselector" name can be convenient: function $ (selector, el) { if (!el) {el = document;} return el.queryselector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.queryselectorall(selector); // note: the returned object is a nodelist. ...
... // if you'd like to convert it to a array for convenience, use this instead: // return array.prototype.slice.call(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(selector); }; a...
...And 2 more matches
2D maze game with device orientation - Game development
eloader will load all of the assets like graphics and audio, mainmenu is the menu with the start button, howto shows the "how to play" instructions and the game state lets you actually play the game. let's quickly go though the content of those states. boot.js the boot state is the first one in the game. ...
...first that will be used later in the preload state to show the progress of loading all the other assets. the create function holds some basic configuration: we're setting up the scaling and alignment of the canvas, and moving on to the preload state when everything's ready. preloader.js the preloader state takes care of loading all the assets: ball.preloader = function(game) {}; ball.preloader.prototype = { preload: function() { this.preloadbg = this.add.sprite((ball._width-297)*0.5, (ball._height-145)*0.5, 'preloaderbg'); this.preloadbar = this.add.sprite((ball._width-158)*0.5, (ball._height-50)*0.5, 'preloaderbar'); this.load.setpreloadsprite(this.preloadbar); this.load.image('ball', 'img/ball.png'); // ... this.load.spritesheet('button-star...
...s is visualized by the framework with the use of one image. with every asset loaded you can see more of the preloadbar image: from 0% to 100%, updated on every frame. after all the assets are loaded, the mainmenu state is launched. mainmenu.js the mainmenu state shows the main menu of the game, where you can start playing by clicking the button. ...
...And 2 more matches
Object building practice - Learn web development
ed to the x/y coordinate values when we animate the balls, to move them by this much on each frame. color — each ball gets a color. size — each ball gets a size — this is its radius, in pixels. this handles the properties, but what about the methods? we want to get our balls to actually do something in our program. drawing the ball first add the following draw() method to the ball()'s prototype: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); } using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2d canvas context we defined earlier (ctx). the context is like the paper, and now we want to command our pen to draw something on...
... members: testball.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas. updating the ball's data we can draw the ball in position, but to actually move the ball, we need an update function of some kind. ...
...all.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas. updating the ball's data we can draw the ball in position, but to actually move the ball, we need an update function of some kind. ...
...And 2 more matches
JSAPI User Guide
_*stub function pointers. */ my_addproperty, my_delproperty, my_getproperty, my_setproperty, my_enumerate, my_resolve, my_convert, my_finalize }; jsobject *obj; /* * define an object named in the global scope that can be enumerated by * for/in loops. the parent object is passed as the second argument, as * with all other api calls that take an object/name pair. the prototype * passed in is null, so the default object prototype will be used. */ obj = js_defineobject(cx, globalobj, "myobject", &my_class, nullptr, jsprop_enumerate); /* * define a bunch of properties with a jspropertyspec array statically * initialized and terminated with a null-name entry. besides its name, * each property has a "tiny" identifier (my_color, e.g.) that can be...
...se my_color: *vp = . . .; break; case my_height: *vp = . . .; break; case my_width: *vp = . . .; break; case my_funny: *vp = . . .; break; case my_array: *vp = . . .; break; case my_rdonly: *vp = . . .; break; } } return true; } defining classes this pulls together the above api elements by defining a constructor function, a prototype object, and properties of the prototype and of the constructor, all with one api call. initialize a class by defining its constructor function, prototype, and per-instance and per-class properties. the latter are called "static" below by analogy to java. they are defined in the constructor object's scope, so that myclass.mystaticprop works along with new myclass(). js_initclass takes a lot of a...
... lot of arguments, but you can pass nullptr for any of the last four if there are no such properties or methods. ...
...And 2 more matches
JS_ConstructObject
moved from the jsapi. the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_new. a less-preferred short-term solution might be to use this reimplementation of the method, but note that this reimplementation is not guaranteed to continue working across spidermonkey releases. create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. syntax jsobject * js_constructobject(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent); jsobject * js_constructobjectwitharguments(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent, unsigned int argc, jsval *argv); name type description cx jscontext ...
...pe description cx jscontext * the context in which to create the new object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp jsclass * pointer to the class to use for the new object. if this is null, an ordinary javascript object is created. proto jsobject * the object to serve as the new object's prototype, or null. parent jsobject * the object to serve as the new object's parent, or null. argc unsigned int (only in js_constructobjectwitharguments) the number of arguments to pass to the constructor. argv jsval * (only in js_constructobjectwitharguments) the array of arguments to pass to the constructor. this may be null if argc is zero. otherwise, the fi...
...l * (only in js_constructobjectwitharguments) the array of arguments to pass to the constructor. this may be null if argc is zero. otherwise, the first argc elements of this array must be populated with valid jsval values. the caller does not need to ensure that the array elements are rooted. description js_constructobject creates a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. cx is a pointer to a context associated with the runtime in which to create the new object. clasp is a pointer to the class of object to create. proto and parent may specify objects to be used as the new object's prototype and parent. if either is null, the engine tries to find reasonable defaults. js_constructobjectwi...
...And 2 more matches
JSAPI reference
e added in spidermonkey 17 js_reporterror js_reportwarning js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: js::createerror added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception js_clearpendingexception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration adde...
...ject js_newobject js_newplainobject added in spidermonkey 38 js_newobjectforconstructor added in spidermonkey 1.8.5 js_newglobalobject added in spidermonkey 1.8 js_newobjectwithgivenproto js_new added in spidermonkey 1.8 js_isglobalobject added in jsapi 24 js_constructobject obsolete since jsapi 16 js_constructobjectwitharguments obsolete since jsapi 16 js_getclass js_getobjectprototype added in jsapi 17 js_getfunctionprototype added in spidermonkey 17 js_getarrayprototype added in spidermonkey 24 js_getconstructor js_getglobalforobject js_getinstanceprivate js_getprototype js_setprototype js_getprivate js_setprivate js_freezeobject added in spidermonkey 1.8.5 js_deepfreezeobject added in spidermonkey 1.8.5 js_isextensible added in spidermonkey 1.8.5 js_preventexten...
...ermonkey 17 js::toprimitiveadded in spidermonkey 45 js::newfunctionfromspecadded in spidermonkey 45 js_defaultvalueobsolete since jsapi 44 js_get_class obsolete since jsapi 13 js_sealobject obsolete since javascript 1.8.5 js_getparent obsolete since jsapi 39 js_setparent obsolete since jsapi 39 standard objects enum jsprotokey added in spidermonkey 24 js_getclassobject js_getclassprototype js::protokeytoid added in spidermonkey 38 js_idtoprotokey added in spidermonkey 31 js::identifystandardinstance added in spidermonkey 31 js::identifystandardprototype added in spidermonkey 31 js::identifystandardinstanceorprototype added in spidermonkey 31 js::identifystandardconstructor added in spidermonkey 38 date js_newdateobject added in spidermonkey 1.8.5 js_newdateobjectmsec ad...
...And 2 more matches
Building an Account Manager Extension
ent the nsiaccountmanagerextension. we name the extension "devmo-account" and state that it is located in the chrome package "example@mozilla.org". furthermore we show the new panel only for imap accounts... components.utils.import("resource://gre/modules/xpcomutils.jsm"); //class constructor function devmoaccountmanagerextension() {}; // class definition devmoaccountmanagerextension.prototype = { name : "devmo-account", chromepackagename : "example@mozilla.org", showpanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") return true; return false; }, queryinterface: xpcomutils.generateqi([ components.interfaces.nsimsgaccountmanagerextension ]) } step 2: building a componen...
...nd register it in the component manager as account manager extension. therefore we add the following code to the previous. the javascript file has to be saved either in the extension's or thunderbird's component directory. // define the contract information needed for this component... // ... the unique component identifier (change it if you copied this example!)... ...
...file has to be saved either in the extension's or thunderbird's component directory. // define the contract information needed for this component... // ... the unique component identifier (change it if you copied this example!)... devmoaccountmanagerextension.prototype.classid = components.id("{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ... the description and ... devmoaccountmanagerextension.prototype.classdescription = "devmo account manager extension"; // ... textual unique identifier or rendez-vous point in the category manager. ...
...And 2 more matches
File - Web APIs
Web › API › File
height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="153.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">file</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor file() returns a newly constructed file. ...
...ace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">file</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor file() returns a newly constructed file. instance properties file.prototype.lastmodified read only returns the last modified time of the file, in millisecond since the unix epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only returns the last modified date of the file referenced by the file object. ...
... #0095dd; pointer-events: all;} constructor file() returns a newly constructed file. instance properties file.prototype.lastmodified read only returns the last modified time of the file, in millisecond since the unix epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only returns the last modified date of the file referenced by the file object. file.prototype.nameread only returns the name of the file referenced by the file object. file.prototype.webkitrelativepath read only returns the path the url of the file is relative to. ...
...And 2 more matches
Border-image generator - CSS: Cascading Style Sheets
lider_right.classname = 'ui-input-slider-right'; if (name) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); this.input = input; sliders[topic] = this; setvalue(topic, value); }; inputslider.prototype.setinputvalue = function setinputvalue() { this.input.value = this.value.tofixed(this.precision) + this.unit; }; var setvalue = function setvalue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; value = parsefloat(value.tofixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; ...
...0 : 1; else this.state = 1 ^ this.state; if (active !== this) { if (active) active.toggle(false); active = this; } if (this.state === 0) this.dropmenu.setattribute('data-hidden', 'true'); else this.dropmenu.removeattribute('data-hidden'); }; var clickout = func...
...!== this) { if (active) active.toggle(false); active = this; } if (this.state === 0) this.dropmenu.setattribute('data-hidden', 'true'); else this.dropmenu.removeattribute('data-hidden'); }; var clickout = function clickout(e) { if (active.state === 0 || e.target === active.dropmenu || e.target === active.select) return; active.toggle(false); }; dropdown.prototype.updatevalue = function updatevalue(e) { if (date.now() - this.time < 500) return; if (e.target.classname !== "ui-dropdown-list") { this.setnodevalue(e.target); this.toggle(false); } this.time = date.now(); }; dropdown.prototype.setnodevalue = function setnodevalue(node) { this.value['name'] = node.textcontent; this.value['value'] = node.getattribute('data-value'); th...
...And 2 more matches
Regular expressions - JavaScript
a variable. advanced searching with flags regular expressions have six optional flags that allow for functionality like global and case insensitive searching. these flags can be used separately or together in any order, and are included as part of the regular expression. regular expression flags flag description corresponding property g global search. ...
...ave six optional flags that allow for functionality like global and case insensitive searching. these flags can be used separately or together in any order, and are included as part of the regular expression. regular expression flags flag description corresponding property g global search. regexp.prototype.global i case-insensitive search. regexp.prototype.ignorecase m multi-line search. ...
...and case insensitive searching. these flags can be used separately or together in any order, and are included as part of the regular expression. regular expression flags flag description corresponding property g global search. regexp.prototype.global i case-insensitive search. regexp.prototype.ignorecase m multi-line search. regexp.prototype.multiline s allows . to match newline characters. ...
...And 2 more matches
Public class fields - JavaScript
ations are an experimental feature (stage 3) proposed at tc39, the javascript standards committee. support in browsers is limited, but the feature can be used through a build step with systems like babel. see the compat information below. both static and instance public fields are writable, enumerable, and configurable properties. as such, unlike their private counterparts, they participate in prototype inheritance. syntax class classwithinstancefield { instancefield = 'instance field' } class classwithstaticfield { static staticfield = 'static field' } class classwithpublicinstancemethod { publicmethod() { return 'hello world' } } examples public static fields public static fields are useful when you want a field to exist only once per class, not on every class instance you ...
...ld.staticfield) // expected output: "static field"​ fields without initializers are initialized to undefined. class classwithstaticfield { static staticfield } console.assert(classwithstaticfield.hasownproperty('staticfield')) console.log(classwithstaticfield.staticfield) // expected output: "undefined" public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain. class classwithstaticfield { static basestaticfield = 'base field' } class subclasswithstaticfield extends classwithstaticfield { static substaticfield = 'sub class field' } console.log(subclasswithstaticfield.substaticfield) // expected output: "sub class field" console.log(subclasswithstaticfield.basestaticfield) // expected output: "base field" when initializing fields, this re...
...d. const prefix = 'prefix' class classwithcomputedfieldname { [`${prefix}field`] = 'prefixed field' } const instance = new classwithcomputedfieldname() console.log(instance.prefixfield) // expected output: "prefixed field" when initializing fields this refers to the class instance under construction. just as in public instance methods, if you're in a subclass you can access the superclass prototype using super. class classwithinstancefield { baseinstancefield = 'base field' anotherbaseinstancefield = this.baseinstancefield baseinstancemethod() { return 'base method output' } } class subclasswithinstancefield extends classwithinstancefield { subinstancefield = super.baseinstancemethod() } const base = new classwithinstancefield() const sub = new subclasswithinstancefield() consol...
...And 2 more matches
Deprecated and obsolete features - JavaScript
irefox 33) escape sequences octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are deprecated. use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters. ...
...nces octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are deprecated. use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters. string methods html wrapper methods like string.prototype.fontsize and string.prototype.big. ...
...quences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are deprecated. use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters. string methods html wrapper methods like string.prototype.fontsize and string.prototype.big. string.prototype.quote is removed from firefox 37. ...
...And 2 more matches
TypeError: More arguments needed - JavaScript
the javascript exception "more arguments needed" occurs when there is an error with how a function is called. more arguments need to be provided. message typeerror: argument is not an object and is not null (edge) typeerror: object.create requires at least 1 argument, but only 0 were passed typeerror: object.setprototypeof requires at least 2 arguments, but only 0 were passed typeerror: object.defineproperties requires at least 1 argument, but only 0 were passed error type typeerror. ...
...totypeof requires at least 2 arguments, but only 0 were passed typeerror: object.defineproperties requires at least 1 argument, but only 0 were passed error type typeerror. what went wrong? there is an error with how a function is called. more arguments need to be provided. ...
...nt wrong? there is an error with how a function is called. more arguments need to be provided. ...
...And 2 more matches
Proxy - JavaScript
lidator); person.age = 100; console.log(person.age); // 100 person.age = 'young'; // throws an exception person.age = 300; // throws an exception extending constructor a function proxy could easily extend a constructor with a new constructor. this example uses the construct and apply handlers. ...
...log(person.age); // 100 person.age = 'young'; // throws an exception person.age = 300; // throws an exception extending constructor a function proxy could easily extend a constructor with a new constructor. this example uses the construct and apply handlers. ...
....age = 'young'; // throws an exception person.age = 300; // throws an exception extending constructor a function proxy could easily extend a constructor with a new constructor. this example uses the construct and apply handlers. ...
...And 2 more matches
Reflect.construct() - JavaScript
the static reflect.construct() method acts like the new operator, but as a function. it is equivalent to calling new target(...args). it gives also the added option to specify a different prototype. 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 reflect.construct(target, argumentslist[, newtarget]) parameters target the target function to call. argumentslist an array-like object specifying the arguments with which target should be called. newtarget optional the constructor whose prototype should be used. see also the new.target operator. if newtarget is not present, its value defaults to target. retu...
....construct() allows you to invoke a constructor with a variable number of arguments. ...
... prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using object.create(). ...
...And 2 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. ...
...le 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 symbol.tostringtag writable no enumerable no configurable no examples default tags object.prototype.tostring.call('foo'); // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ... and more built-in tost...
... // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ... and more built-in tostringtag symbols object.prototype.tostring.call(new map()); // "[object map]" object.prototype.tostring.call(function* () {}); // "[object generatorfunction]" object.prototype.tostring.call(promise.resolve()); // "[object promise]" // ... ...
...And 2 more matches
SyntaxError - JavaScript
the syntaxerror object represents an error when trying to interpret syntactically invalid code. it is thrown when the javascript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code. constructor syntaxerror() creates a new syntaxerror object. instance properties syntaxerror.prototype.message error message. ...
...t is thrown when the javascript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code. constructor syntaxerror() creates a new syntaxerror object. instance properties syntaxerror.prototype.message error message. although ecma-262 specifies that syntaxerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. syntaxerror.prototype.name error name. inherited from error. syntaxerror.prototype.filename path to file that raised this error. ...
...inherited from error. ...
...And 2 more matches
for...in - JavaScript
for (variable in object) statement variable a different property name 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 loo...
...for...in will return the indexes in any particular order. the for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited. because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. therefore, it is better to use a for loop with a numeric index (or array.prototype.foreach() or the for...of loop) when iterating over arrays where the order of access is important. iterating over own properties only if you only want to consider properties attached to the object itself, and not its prototypes, use getownpropertynames() or perform a hasownproperty() check (propertyisenumerable() can also be used). alternatively, if you know there won't be any outside code inte...
...hen iterating over arrays where the order of access is important. iterating over own properties only if you only want to consider properties attached to the object itself, and not its prototypes, use getownpropertynames() or perform a hasownproperty() check (propertyisenumerable() can also be used). alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method. ...
...And 2 more matches
for...of - JavaScript
in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { ...
...over something. the main difference between them is in what they iterate over. the for...in statement iterates over the enumerable properties of an object, in an arbitrary order. the for...of statement iterates over values that the iterable object defines to be iterated over. the following example shows the difference between a for...of loop and a for...in loop when used with an array. ...
... them is in what they iterate over. the for...in statement iterates over the enumerable properties of an object, in an arbitrary order. the for...of statement iterates over values that the iterable object defines to be iterated over. the following example shows the difference between a for...of loop and a for...in loop when used with an array. ...
...And 2 more matches
core/namespace - Archive of obsolete content
aces for objects, which effectively may be used for creating fields that are not part of objects public api. let { ns } = require('sdk/core/namespace'); let anamespace = ns(); anamespace(publicapi).secret = secret; one namespace may be used with multiple objects: let { ns } = require('sdk/core/namespace'); let dom = ns(); function view(element) { let view = object.create(view.prototype); dom(view).element = element; // .... } view.prototype.destroy = function destroy() { let { element } = dom(this); element.parentnode.removechild(element); // ... }; // ... exports.view = view; // ... also, multiple namespaces can be used with one object: // ./widget.js let { cu } = require('chrome'); let { ns } = require('sdk/core/namespace'); let { vi...
...tiple namespaces can be used with one object: // ./widget.js let { cu } = require('chrome'); let { ns } = require('sdk/core/namespace'); let { view } = require('./view'); // note this is completely independent from view's internal namespace object. ...
...ew } = require('./view'); // note this is completely independent from view's internal namespace object. let sandboxes = ns(); function widget(options) { let { element, contentscript } = options; let widget = object.create(widget.prototype); view.call(widget, options.element); sandboxes(widget).sandbox = cu.sandbox(element.ownerdocument.defaultview); // ... } widget.prototype = object.create(view.prototype); widget.prototype.postmessage = function postmessage(message) { let { sandbox } = sandboxes(this); sandbox.postmessage(json.stringify(json.parse(message))); ... }; widget.prototype.destroy = function destroy() { view.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.widget = widget; in addition access...
...dbox.postmessage(json.stringify(json.parse(message))); ... }; widget.prototype.destroy = function destroy() { view.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.widget = widget; in addition access to the namespace can be shared with other code by just handing them a namespace accessor function. ...
core/promise - Archive of obsolete content
async(url); timeout(tweets, 20).then(function(data) { ui.display(data); }, function() { alert('network is being too slow, try again later'); }); alternative promise apis there may be cases where you will want to provide more than just then method on your promises. in fact some other promise frameworks do that. such use cases are also supported. ...
... being too slow, try again later'); }); alternative promise apis there may be cases where you will want to provide more than just then method on your promises. in fact some other promise frameworks do that. such use cases are also supported. earlier described defer may be passed optional prototype argument, in order to make the returned promise and all the subsequent promises decendents of that prototype: let { promise, resolve } = defer({ get: function get(name) { return this.then(function(value) { return value[name]; }); } }); promise.get('foo').get('bar').then(console.log); resolve({ foo: { bar: 'taram !!' } }); // => 'taram !!' also promised function maybe be passed a second optional prototype argument to achieve the same effect. treat all values as promises module pro...
...r second = resolve(b).then(function(bvalue) { return !!bvalue }); return resolve(a).then(function(avalue) { return !!avalue || second; }, function() { return second; }) } note: we could not use promised function here, as they reject returned promise if any of the given arguments is rejected. if you need to customize your promises even further you may pass resolve a second optional prototype argument that will have same effect as with defer. treat errors as promises now that we can create all kinds of eventual values, it's useful to have a way to create eventual errors. module exports reject to do exactly that. it takes anything as an argument and returns a promise that is rejected with it. const { reject } = require('sdk/core/promise'); var boom = reject(error('boom!')); future...
... it's useful to have a way to create eventual errors. module exports reject to do exactly that. it takes anything as an argument and returns a promise that is rejected with it. const { reject } = require('sdk/core/promise'); var boom = reject(error('boom!')); future(function() { return math.random() < 0.5 ? boom : value }) as with the rest of the apis a reject may be given a second optional prototype argument to customize resulting promise to your needs. ...
Canvas code snippets - Archive of obsolete content
}; } chaining methods this class provides jquery-style chained access to 2d context methods and properties. ...
...rgradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokestyle', 'textalign', 'textbaseline']; for (let m of methods) { let method = m; canvas2dcontext.prototype[method] = function() { this.ctx[method].apply(this.ctx, arguments); return this; }; } for (let m of gettermethods) { let method = m; canvas2dcontext.prototype[method] = function() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; canvas2dcontext.prototype[prop] = function(value) { if (value ===...
...rence to the iframe's window and draws this window to a canvas object. note that this only works if you are running the page from chrome. if you try running the code as a plain webpage, you will get a 'security error" code: "1000' error. remotecanvas = function() { this.url = 'http://developer.mozilla.org'; }; remotecanvas.canvas_width = 300; remotecanvas.canvas_height = 300; remotecanvas.prototype.load = function() { var windowwidth = window.innerwidth - 25; var iframe; iframe = document.createelement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowwidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // here is where the magic happens... add a listener to the // frame's onload event iframe.ad...
... iframe.height = '10px'; iframe.width = windowwidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // here is where the magic happens... ...
Appendix D: Loading Scripts - Archive of obsolete content
s, including the url, line number, and javascript version of the file from which the code being evaluated was extracted. this information is invaluable for debugging, and the flexibility with which it can be specified makes this method useful for extracting javascript from a number of file formats other than raw javascript scripts. additionally, as sandbox objects can be created with an arbitrary prototype object, the evaluated code can be given access to the global properties of any existing scope. security: sandbox objects are initialized with a security principal object, or otherwise a window or url from which to derive one. this means that evalinsandbox can be used to execute code with a specified privilege level rather than full chrome privileges. beyond this, the scope of the sandbox can be ...
... // use the current content window as the execution context. // to make properties defined by scripts executing on the page // available to your sandbox script, use content.wrappedjsobject // instead. let context = content; // create the sandbox let sandbox = components.utils.sandbox(context, { // make properties of the context object available via the // script's global scope sandboxprototype: context, // wrap objects retrieved from the sandbox in xpcnativewrappers. // this is the default action. wantxrays: true }); // the script that will be executed: let script = string(); // evaluate the script: components.utils.evalinsandbox(script, sandbox, // the javascript version "1.8", /...
...ut will still be wrapped in inter-compartment proxies. ...
...e current script and will have access to the same globals, but any new globals it creates will be accessible only to the script itself. objects passed out of the sandbox will not be wrapped in xpcnativewrappers but will still be wrapped in inter-compartment proxies. ...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
, and es2018 have been released. this year, the es2019 specification will be released and es2020 is the current ecmascript draft specification. you can see the latest proposals on the tc39/ecma262 github repository. a channel for feedback on ecmascript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ...
...e es2019 specification will be released and es2020 is the current ecmascript draft specification. you can see the latest proposals on the tc39/ecma262 github repository. a channel for feedback on ecmascript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ...
...pository. a channel for feedback on ecmascript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ...
...cript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
codingscripting, glossary, javascript in javascript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. there are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. there also is null, which is seemingly primitive, but indeed is a special case for every object: and any structured type is derived from null by the prototype chain. 332 privileged glossary, security users are said to be privileged when they are granted additional rights to a system, or given ultimate access to content in a higher priority level when compared to normal users. 333 progressive enhancement accessibility, design, glossary progressive enhancement is a design philosophy that provides a baseline of es...
... attributes associated with a data structure. 339 protocol glossary, infrastructure, protocols a protocol is a system of rules that define how data is exchanged within or between computers. communications between devices require that the devices agree on the format of the data that is being exchanged. the set of rules that defines a format is called a protocol. ...
... 339 protocol glossary, infrastructure, protocols a protocol is a system of rules that define how data is exchanged within or between computers. communications between devices require that the devices agree on the format of the data that is being exchanged. the set of rules that defines a format is called a protocol. ...
... between computers. communications between devices require that the devices agree on the format of the data that is being exchanged. the set of rules that defines a format is called a protocol. 340 prototype apps, composing, glossary a prototype is a model that displays the appearance and behavior of an application or product early in the development lifecycle. 341 prototype-based programming codingscripting, glossary prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first definin...
Index - Learn web development
learn, oojs, object-oriented, objects, l10n:priority in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it. 66 inheritance in javascript article, beginner, codingscripting, constructor, function, getter, inheritance, javascript, learn, oojs, oop, object, object member, prototype, extends, l10n:priority, setter this article has covered the remainder of the core oojs theory and syntax that we think you should know now. at this point you should understand javascript object and oop basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes. ...
...ng practice article, beginner, canvas, codingscripting, guide, javascript, learn, objects, tutorial, l10n:priority we hope you had fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module! this should have given you some useful practice in using objects, and good real world context. ...
...l, l10n:priority we hope you had fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module! this should have given you some useful practice in using objects, and good real world context. 69 object prototypes article, beginner, codingscripting, constructor, javascript, learn, oojs, oop, object, prototype, prototype chaining, create(), l10n:priority this article has covered javascript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors, and other related topics. 70 object-oriented javascript for beginners article, beginner, codingscripting, cons...
...cript, learn, objects, test your skills this aim of this skill test is to assess whether you've understood our javascript object basics article. 73 test your skills: object-oriented javascript beginner, javascript, learn, oojs, objects, test your skills the aim of this skill test is to assess whether you've understood our object-oriented javascript for beginners, object prototypes, and inheritance in javascript articles. 74 working with json article, beginner, codingscripting, guide, json, json api, json arrays, json parsing, json structure, javascript, learn, objects, tutorial, l10n:priority in this article, we've given you a simple guide to using json in your programs, including how to create and parse json, and how to access data locked inside it. ...
Adding features to our bouncing balls demo - Learn web development
exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). this should be a boolean (true/false). the ball() constructor should inherit the x, y, velx, vely, and exists properties from the shape() constructor. it should also define a color and a size property, like the original ball() constructor did. remember to set the ball() constructor's prototype and constructor appropriately. the ball draw(), update(), and collisiondetect() method definitions should be able to stay exactly the same as they were before. you also need to add a new parameter to the new ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true. at this point, try reloading the code — it should work just th...
...ment. the evilcircle() constructor should inherit x, y, velx, vely, and exists from shape(), but velx and vely should always equal 20. you should do this something like shape.call(this, x, y, 20, 20, exists); it should also define its own properties, as follows: color — 'white' size — 10 again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly. defining evilcircle()'s methods evilcircle() should have four methods, as described below. draw() this method has the same purpose as ball()'s draw() method: it draws the object instance on the canvas. it will work in a very similar way, so you can start by copying the ball.prototype.draw definition. you should then make the following changes: we want ...
...u can see the evil circle a bit more easily. this can be achieved by setting a value for linewidth somewhere after the beginpath() call (3 will do). checkbounds() this method will do the same thing as the first part of ball()'s update() function — look to see whether the evil circle is going to go off the edge of the screen, and stop it from doing so. again, you can mostly just copy the ball.prototype.update definition, but there are a few changes you should make: get rid of the last two lines — we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below. inside the if() statements, if the tests return true we don't want to update velx/vely; we want to instead change the value of x/y so the evil circ...
...n online shareable editor (as mentioned in step 1 above). ...
How to implement a custom autocomplete search component
am {array.<string>|null=} comments */ function providerautocompleteresult(searchstring, searchresult, defaultindex, errordescription, results, comments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._errordescription = errordescription; this._results = results; this._comments = comments; } providerautocompleteresult.prototype = { _searchstring: "", _searchresult: 0, _defaultindex: 0, _errordescription: "", _results: [], _comments: [], /** * @return {string} the original search string */ get searchstring() { return this._searchstring; }, /** * @return {number} the result code of this result object, either: * result_ignored (invalid searchstring) * result_failure (failure...
..., removefromdb) { this._results.splice(index, 1); if (this._comments) this._comments.splice(index, 1); }, getlabelat: function(index) { return this._results[index]; }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompleteresult ]) }; /** * @constructor * * @implements {nsiautocompletesearch} */ function providerautocompletesearch() { } providerautocompletesearch.prototype = { classid: class_id, classdescription : class_name, contractid : contract_id, /** * searches for a given string and notifies a listener (either synchronously * or asynchronously) of the result * * @param searchstring the string to search for * @param searchparam an extra parameter * @param previousresult a previous result to use for faster searchinig * @param list...
...leteresult(searchstring, searchresult, defaultindex, errordescription, results, comments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._errordescription = errordescription; this._results = results; this._comments = comments; } simpleautocompleteresult.prototype = { _searchstring: "", _searchresult: 0, _defaultindex: 0, _errordescription: "", _results: [], _comments: [], /** * the original search string */ get searchstring() { return this._searchstring; }, /** * the result code of this result object, either: * result_ignored (invalid searchstring) * result_failure (failure) * result_...
...ndex, removefromdb) { this._results.splice(index, 1); this._comments.splice(index, 1); }, queryinterface: function(aiid) { if (!aiid.equals(ci.nsiautocompleteresult) && !aiid.equals(ci.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; // implements nsiautocompletesearch function simpleautocompletesearch() { } simpleautocompletesearch.prototype = { /* * search for a given string and notify a listener (either synchronously * or asynchronously) of the result * * @param searchstring - the string to search for * @param searchparam - an extra parameter * @param previousresult - a previous result to use for faster searchinig * @param listener - a listener to notify when the search is complete */ startsearch: functi...
sslfnc.html
t up by ssl_authcertificatehook is called to authenticate an incoming certificate. if the checksig parameter is set to pr_true, the callback function also verifies the digital signature. note: if you do not call ssl_authcertificatehook to supply a certificate authentication callback function, ssl uses the default callback function, ssl_authcertificate. the callback function has the following prototype: typedef secstatus (*sslauthcertificate) ( void *arg, prfiledesc *fd, prbool checksig, prbool isserver); this callback function has the following parameters: arg a pointer supplied by the application (in the call to ssl_authcertificatehook) that can be used to pass state information. can be null. fd a pointer to the file...
...ficate callback function gives the program an opportunity to do something (for example, log the attempt or authorize the certificate) when certificate authentication is not successful. if such a callback function is not provided by the application, the ssl connection simply fails when certificate authentication is not successful. the callback function set up by ssl_badcerthook has the following prototype: typedef secstatus (*sslbadcerthandler)( void *arg, prfiledesc *fd); this callback function has the following parameters: arg the arg parameter passed to ssl_badcerthook. fd a pointer to the file descriptor for the ssl socket. the callback function returns one of these values: secsuccess: the callback has cho...
...d by the server. the callback function retrieves the client's private key and certificate. ssl provides an implementation of this callback function; see nss_getclientauthdata for details. unlike ssl_authcertificate, nss_getclientauthdata is not a default callback function. you must set it explicitly with ssl_getclientauthdatahook if you want to use it. the callback function has the following prototype: typedef secstatus (*sslgetclientauthdata)( void *arg, prfiledesc *fd, certdistnames *canames, certcertificate **pretcert, seckeyprivatekey **pretkey); this callback function has the following parameters: arg the arg parameter passed to ssl_getclientauthdatahook. fd a pointer to the file descriptor for the ssl socket...
.... client_data a pointer to the value of the client_data argument that was passed to ssl_handshakecallback. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. description the callback function set by ssl_handshakecallback has the following prototype: typedef void (*sslhandshakecallback)( prfiledesc *fd, void *client_data); this callback function has the following parameters: fd a pointer to the file descriptor for the ssl socket. client_data a pointer supplied by the application that can be used to pass state information. can be null. see also ssl commun...
Rhino scopes and contexts
expensive method to call and it allocates a fair amount of memory. we'll see below that there are ways to share a scope created this way among multiple scopes and threads. name lookup so how are scopes used to look up names? in general, variables are looked up by starting at the current variable object (which is different depending on what code is being executed in the program), traversing its prototype chain, and then traversing the parent chain. in the diagram below, the order in which the six objects are traversed is indicated. order of lookups in a two-deep scope chain with prototypes. for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a new top-l...
...n is traversed looking for a 'x' property. when none is found, a new property 'x' is created in the top-level scope. sharing scopes javascript is a language that uses delegation rather than traditional class-based inheritance. this is a large topic in itself, but for our purposes it gives us an easy way to share a set of read-only variables across multiple scopes. to do this we set an object's prototype. when accessing a property of an object in javascript, the object is first searched for a property with the given name. if none is found, the object's prototype is searched. this continues until either the object is found or the end of the prototype chain is reached. so to share information across multiple scopes, we first create the object we wish to share. typically this object will have been ...
...pe is searched. this continues until either the object is found or the end of the prototype chain is reached. so to share information across multiple scopes, we first create the object we wish to share. typically this object will have been created with initstandardobjects and may also have additional objects specific to the embedding. then all we need to do is create a new object and call its setprototypemethod to set the prototype to the shared object, and the parent of the new scope to null: scriptable newscope = cx.newobject(sharedscope); newscope.setprototype(sharedscope); newscope.setparentscope(null); the call to newobject simply creates a new javascript object with no properties. it uses thesharedscope passed in to initialize the prototype with the standard object.prototype value. we ca...
...ess to when it references a variable? the answer to 1 determines which scope should be the ultimate parent scope: rhino follows the parent chain up to the top and places the variable there. after you've constructed your parent scope chain, the answer to question 2 may indicate that there are additional scopes that need to be searched that are not in your parent scope chain. you can add these as prototypes of scopes in your parent scope chain. when rhino looks up a variable, it starts in the current scope, walks the prototype chain, then goes to the parent scope and its prototype chain, until there are no more parent scopes left. ...
JSAPI Cookbook
ropfunc, enumerable: true}); in the jsapi version, to signify that the property is read-only, pass null for the setter. ...
...n the jsapi version, to signify that the property is read-only, pass null for the setter. /* jsapi */ if (!js_defineproperty(cx, obj, "prop", js::undefinedvalue(), getpropfunc, null, jsprop_shared | jsprop_native_accessors | jsprop_enumerate)) { return false; } working with the prototype chain defining a native read-only property on the string.prototype // javascript object.defineproperty(string.prototype, "md5sum", {get: getmd5func, enumerable: true}); the following trick couldn't work if someone has replaced the global string object with something. /* jsapi */ jsobject *string; jsobject *string_prototype; js::value val; // get the string constructor from the global object. if (!js_getpro...
...laced the global string object with something. /* jsapi */ jsobject *string; jsobject *string_prototype; js::value val; // get the string constructor from the global object. if (!js_getproperty(cx, global, "string", &val)) return false; if (jsval_is_primitive(val)) return throwerror(cx, global, "string is not an object", __file__, __line__); string = jsval_to_object(val); // get string.prototype. if (!js_getproperty(cx, string, "prototype", &val)) return false; if (jsval_is_primitive(val)) return throwerror(cx, global, "string.prototype is not an object", __file__, __line__); string_prototype = jsval_to_object(val); // ...and now we can add some new functionality to all strings. ...
... actually outputting errors. how to write your own jsclass with reserved slots. ...
JS::IdentifyStandardInstance
this article covers features introduced in spidermonkey 31 determine if the given object is an instance/prototype/constructor for a standard class. syntax jsprotokey js::identifystandardinstance(jsobject *obj); jsprotokey js::identifystandardprototype(jsobject *obj); jsprotokey js::identifystandardinstanceorprototype(jsobject *obj); jsprotokey js::identifystandardconstructor(jsobject *obj); // added in spidermonkey 38 name type description obj jsobject * pointer to the instance/prototype/constructor object to determine. description js::identifystandardinstance determines if the given object is an instance for a standard class. ...
...constructor(jsobject *obj); // added in spidermonkey 38 name type description obj jsobject * pointer to the instance/prototype/constructor object to determine. description js::identifystandardinstance determines if the given object is an instance for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardprototype determines if the given object is a prototype for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardinstanceorprototype determines if the given object is an instance or prototype for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardconstructor determines if the given object is a ...
... object is an instance or prototype for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardconstructor determines if the given object is a constructor for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. ...
...f so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardconstructor determines if the given object is a constructor for a standard class. if so, return the associated jsprotokey. ...
JSClass.flags
, but in spidermonkey the global object is the last object in the scope chain, which can be different objects at different times. this is actually quite subtle. js_executescript and similar apis set the global object for the code they execute. ...
...milar apis set the global object for the code they execute. js_setglobalobject sets an object which is sometimes used as the global object, as a last resort.) enable standard ecmascript behavior for setting the prototype of certain objects, such as function objects. if the global object does not have this flag, then scripts may cause nonstandard behavior by replacing standard constructors or prototypes (such as function.prototype.) objects that can end up with the wrong prototype object, if this flag is not present, include: arguments objects (ecma 262-3 §10.1.8 specifies "the original object prototype"), function objects (ecma 262-3 §13.2 specifies "the original function prototype"), and objects created by many standard constructors (ecma 262-3 §15.4.2.1 and others). mxr id searc...
...'s resolve hook is actually a jsnewresolveop, not a jsresolveop. jsclass_share_all_properties obsolete since javascript 1.8.5 instructs spidermonkey to automatically give all properties of objects of this class the jsprop_shared attribute. jsclass_new_resolve_gets_start obsolete since jsapi 16 the resolve hook expects to receive the starting object in the prototype chain passed in via the *objp in/out parameter. (this is meaningful only if the jsclass_new_resolve flag is also set.) jsclass_construct_prototype obsolete since jsapi 11 instructs js_initclass to invoke the constructor when creating the class prototype. jsclass_is_extended obsolete since jsapi 17indicates that this jsclass is really a jsextendedclass. ...
...its internal use. they are jsclass_is_anonymous, jsclass_is_global, jsclass_is_proxy, and jsclass_has_cached_proto. jsapi applications should not use these flags. ...
Shell global objects
w scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. sourcemapurl if present with value v, convert v to a string, and provide that as the code's source map url. if omitted, attach no source map url to the code (although the code may provide one itself, via a //#sourcemappingurl comment). sourceislazy if present and true, indicates that, after compilation, script source should not be cached by the js engine and ...
...ing column number for error messages and debug info element if present with value v, convert v to an object o and mark the source as being attached to the dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. runoffthreadscript() wait for off-thread compilation to complete. if an error occurred, throw the appropriate exception; otherwise, run the script and return its value. offthreadcompilemodule(code) compile code on a helper thread. to wait for the compilation to finish and get the module object, call finishoffthreadmodule. finishoffthreadmodule() wait for of...
...trieve the source code for compilations that occurred long before it was set, and that it knows nothing about. the reverse applies as well: the original hook, that we reinstate after the call to fun completes, might be asked for the source code of compilations that fun performed, and which, presumably, only hook knows how to find. wrapwithproto(obj) wrap an object into a noop wrapper with prototype semantics. note: this is not fuzzing safe because it can be used to construct deeply nested wrapper chains that cannot exist in the wild. trackedopts(fun) returns an object describing the tracked optimizations of fun, if any. if fun is not a scripted function or has not been compiled by ion, null is returned. dumpscopechain(obj) prints the scope chain of an interpreted function or a module. ...
...olean properties options.args - show arguments to each function options.locals - show local variables in each frame options.thisprops - show the properties of the this object of each frame bytesize(value) return the size in bytes occupied by value, or undefined if value is not allocated in memory. bytesizeofscript(f) return the size in bytes occupied by the function f's jsscript. setimmutableprototype(obj) try to make obj's [[prototype]] immutable, such that subsequent attempts to change it will fail. return true if obj's [[prototype]] was successfully made immutable (or if it already was immutable), false otherwise. throws in case of internal error, or if the operation doesn't even make sense (for example, because the object is a revoked proxy). setlazyparsingdisabled(bool) explicitly disa...
XPCOM changes in Gecko 2.0
5-a4d2-3d4bde0f7ef8} category profile-after-change mycomponent @foobar/mycomponent;1 the javascript code no longer exports a nsgetmodule() function. it now must export a nsgetfactory() function, which accepts a class id (cid) as a parameter. ...
...sm"); function mycomponent() { } mycomponent.prototype = { // this must match whatever is in chrome.manifest! classid: components.id("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}"), queryinterface: xpcomutils.generateqi([components.interfaces.nsimycomponent]), /* nsimycomponent implementation goes here */ ... }; // the following line is what xpcom uses to create components. each component prototype // must have a .classid which is used to create it. const nsgetfactory = xpcomutils.generatensgetfactory([mycomponent]); a component may implement backwards compatibility with gecko 1.9.2 by dynamically detecting which symbols are exported by xpcomutils.jsm and exporting the correct function: /** * xpcomutils.generatensgetfactory was introduced in mozilla 2 (firefox 4, seamonkey 2.1). * xpcomuti...
...en migrating to chrome.manifest. changed category names the xpcom category manager is used to register certain global helper objects. because chrome.manifest is a space-delimited format, category names with spaces cannot be registered. ...
...ory names the xpcom category manager is used to register certain global helper objects. because chrome.manifest is a space-delimited format, category names with spaces cannot be registered. ...
nsIHttpHeaderVisitor
ce in javascript and uses it to evaluate the mime type of a http response. this is done by subscribing to the http-on-examine-response and http-on-examine-cached-response observers. when the observer fires, the visitor interface is used to walk through the response headers and evaluate the mime type. ...
...valuate the mime type. ...
...totype.isflash = function ( ) { return this._isflash; }; myhttprequestobserver = function ( ) { this.register( ); this.aborted = components.results.ns_binding_aborted; this.nsihttpchannel = components.interfaces.nsihttpchannel; this.nsichannel = components.interfaces.nsichannel; this.nsirequest = components.interfaces.nsirequest; }; myhttprequestobserver.prototype.observe = function ( subject, topic, data ) { var uri, avisitor; if ( subject instanceof this.nsihttpchannel ) { avisitor = new mynsihttpheadervisitor( ); subject.visitresponseheaders( avisitor ); if ( avisitor.isflash( ) ) { uri = subject.uri; subject.cancel( this.aborted ); alert( "found flash!
... if ( subject instanceof this.nsihttpchannel ) { avisitor = new mynsihttpheadervisitor( ); subject.visitresponseheaders( avisitor ); if ( avisitor.isflash( ) ) { uri = subject.uri; subject.cancel( this.aborted ); alert( "found flash!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.addobserver(this, "http-on-examine-response", false); observerservice.addobserver(this, "http-on-examine-cached-response", false); }; myhttprequestobserver.prototype.unregister = function ( ) { ...
nsIXPCScriptable
constants constant value description want_precreate 1 << 0 want_create 1 << 1 want_postcreate 1 << 2 want_addproperty 1 << 3 want_delproperty 1 << 4 ...
...no implementor of this interface should ever return flags with this bit set. methods precreate() void precreate( in nsisupports nativeobj, ...
...no implementor of this interface should ever return flags with this bit set. methods precreate() void precreate( in nsisupports nativeobj, in jscontextptr cx, in jsobje...
...lse to indicate failure. newresolve() this method is called when the want_newresolve flag is set. when this method is called, xpconnect is attempting to resolve a lazy property named by id on obj. the js engine will check if the property named by id is defined after this method has been called. this is very similar to jsnewresolveop. if an implementation of this method throws an error code, the prototype chain will not be checked for the property. prbool newresolve( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 flags, out jsobjectptr objp ); parameters wrapper cx the pointer to the jscontext newresolve is being called from. obj the pointer to the jsobject that the property named by id that is being accessed. id ...
Debugger - Firefox Developer Tools
the debugger object when called as a constructor, the debugger object creates a new debugger instance. new debugger([global, …]) create a debugger object, and apply its adddebuggee method to each of the givenglobal objects to add them as the initial debuggees. accessor properties of the debugger prototype object a debugger instance inherits the following accessor properties from its prototype: enabled a boolean value indicating whether this debugger instance’s handlers, breakpoints, and the like are currently enabled. it is an accessor property with a getter and setter: assigning to it enables or disables this debugger instance; reading it produces true if the instance is enabled, or false otherwise. this property is initially true in a freshly created debugger instance. ...
...lity-based restrictions on a debugger’s reach. however, the onnewglobalobject method allows the api user to monitor all global object creation that occurs anywhere within the javascript system (the “jsruntime”, in spidermonkey terms), thereby escaping the capability-based limits. for this reason, onnewglobalobject is only available to privileged code. function properties of the debugger prototype object the functions described below may only be called with a this value referring to a debugger instance; they may not be used as methods of other kinds of objects. adddebuggee(global) add the global object designated byglobal to the set of global objects this debugger instance is debugging. if the designated global is already a debuggee, this has no effect. return this debugger’s debu...
... objects are returned; an object must meet all the criteria given by query to be returned. if query is omitted, we return the debugger.object instances for all objects allocated in the scope of debuggee globals. the query object may have the following properties: class if present, only return objects whose internal [[class]]’s name matches the given string. note that in some cases, the prototype object for a given constructor has the same [[class]] as the instances that refer to it, but cannot itself be used as a valid instance of the class. code gathering objects by class name may need to examine them further before trying to use them. all properties of query are optional. passing an empty object returns all objects in debuggee globals. unlike findscripts, this function is determi...
...ased limits. for this reason, findallglobals is only available to privileged code. makeglobalobjectreference(global) return the debugger.object whose referent is the global object designated byglobal, without adding the designated global as a debuggee. ifglobal does not designate a global object, throw a typeerror. determine which global is designated byglobal using the same rules as debugger.prototype.adddebuggee. adoptdebuggeevalue(value) given a debuggee value value owned by an arbitrary debugger, return an equivalent debuggee value owned by this debugger. if value is a primitive value, return it unchanged. if value is a debugger.object owned by an arbitrary debugger, return an equivalent debugger.object owned by this debugger. otherwise, if value is some other kind of object, and henc...
Element.hasAttribute() - Web APIs
e() method returns a boolean value indicating whether the specified element has the specified attribute or not. syntax var result = element.hasattribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
...s a boolean value indicating whether the specified element has the specified attribute or not. syntax var result = element.hasattribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
...ing whether the specified element has the specified attribute or not. syntax var result = element.hasattribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
...true or false. name is a string representing the name of the attribute. ...
Node.hasChildNodes() - Web APIs
nodes() method returns a boolean value indicating whether the given node has child nodes or not. syntax bool = node.haschildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise. ...
...returns a boolean value indicating whether the given node has child nodes or not. syntax bool = node.haschildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise. ...
...dicating whether the given node has child nodes or not. syntax bool = node.haschildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise. ...
...ildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise. example let foo = document.getelementbyid('foo'); if (foo.haschildnodes()) { // do something with 'foo.childnodes' } polyfill here is one possible polyfill: ;(function(prototype) { prototype.haschildnodes = prototype.haschildnodes || function() { return !!this.firstchild; } })(node.prototype); there are various ways to determine whether the node has a child node: node.haschildnodes() node.firstchild != null (or just node.firstchild) node.childnodes && node.childnodes.length (or node.childnodes.length > 0) specifications specification status comment domthe definition of 'node: haschildnodes' in that specification. living standard ...
ParentNode.children - Web APIs
nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation. if the node has no element children, then children is an empty list with a length of 0. example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. ...
... empty list with a length of 0. example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. // adds document & documentfragment support for ie9 & safari. // returns array instead of htmlcollection. ...
...0. example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. // adds document & documentfragment support for ie9 & safari. // returns array instead of htmlcollection. ...
...= 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. // adds document & documentfragment support for ie9 & safari. // returns array instead of htmlcollection. ...
ParentNode.firstElementChild - Web APIs
l change that shouldn't affect compatibility. syntax var element = node.firstelementchild; example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> var foo = document.getelementbyid('foo'); // yields: first (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype. ...
... <li>second (2)</li> <li>third (3)</li> </ul> <script> var foo = document.getelementbyid('foo'); // yields: first (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype. // adds document & documentfragment support for ie9 & safari. ...
... (3)</li> </ul> <script> var foo = document.getelementbyid('foo'); // yields: first (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype. // adds document & documentfragment support for ie9 & safari. ...
...rst (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype. // adds document & documentfragment support for ie9 & safari. ...
ParentNode.lastElementChild - Web APIs
hild example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. ...
...foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // returns array instead of htmlcollection. ...
...('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // returns array instead of htmlcollection. ...
.../script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // returns array instead of htmlcollection. ...
ARIA: grid role - Accessibility
tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); ...
....call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.datase...
... #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); ...
....call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.datase...
Overview of events and handlers - Developer guides
easily be followed using completely custom code, as explained in the article on custom events. the pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity. modern web browsers follow the event pattern using a standardized approach. browsers use as the data structure for the properties of the event, an object derived from the eventprototype object. browsers use as the registration method for the function which will handle those data structures a method called addeventlistener which expects as arguments a string event type name and the handler function. finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects. button event handler demo for example, browse...
...ck' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. ...
... mouse click or, when displayed in touch sensitive surfaces, to a finger tap. ...
...hed loading, the dom node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the dom node in the html page. the event object hierarchy the web browser defines many events of different kinds. each definition includes, as the data structure passed to the handler function, an object which inherits from the eventprototype object. a partial diagram of the class hierarchy of event objects is: note: this diagram is incomplete. the web api documentation contains a page defining the event object which also includes the known dom event subclasses of the event object. documents three sources on the mdn (mozilla developer network) web site are particularly useful for programmers wanting to work with events: th...
Equality comparisons and sameness - JavaScript
which operation you choose depends on what sort of comparison you are looking to perform. briefly: double equals (==) w...
... which operation you choose depends on what sort of comparison you are looking to perform. briefly: double equals (==) w...
... which operation you choose depends on what sort of comparison you are looking to perform. briefly: double equals (==) w...
... which operation you choose depends on what sort of comparison you are looking to perform. briefly: double equals (==) w...
constructor - JavaScript
for the polygon's width and height super(length, length); // note: in derived classes, `super()` must be called before you // can use `this`. leaving this out will cause a referenceerror. ...
...ue**0.5; this.width = value**0.5; } } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a square is created. ...
...idth = value**0.5; } } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a square is created. ...
...} } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a square is created. class polygon { constructor() { this.name = "polygon"; } } class square extends polygon { constructor() { super(); } } class rectangle {} object.setprototypeof(square.prototype, rectangle.prototype); console.log(object.getprototypeof(square.prototype) === polygon.prototype); //false console.log(object.getprototypeof(square.prototype) === rectangle.prototype); //true let newinstance = new square(); console.log(newinstance.name); //polygon specifications specification ecmascript (ecma-262)the definition of 'constructor method' in that specification. ...
Intl.DateTimeFormat - JavaScript
ase clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.datetimeformat() creates a new datetimeformat object. static methods intl.datetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. ...
...t. static methods intl.datetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.datetimeformat.prototype.format() getter function that formats a date according to the locale and formatting options of this datetimeformat object. intl.datetimeformat.prototype.formattoparts() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting. ...
...ck to the runtime's default locale. instance methods intl.datetimeformat.prototype.format() getter function that formats a date according to the locale and formatting options of this datetimeformat object. intl.datetimeformat.prototype.formattoparts() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting. intl.datetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. ...
...ns of this datetimeformat object. intl.datetimeformat.prototype.formattoparts() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting. intl.datetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. intl.datetimeformat.prototype.formatrange() this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating datetimeformat. intl.datetimeformat.prototype.formatrangetoparts() this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. examples using da...
Promise - JavaScript
alue, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's then method are called. if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. as the promise.prototype.then() and promise.prototype.catch() methods return promises, they can be chained. not to be confused with: several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. scheme. promises in javascript represent processes that are already happening, which can be chained with callback functions. if you are looking to lazily evalua...
... resolved with the given value. if the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. generally, if you don't know if a value is a promise or not, promise.resolve(value) it instead and work with the return value as a promise. ...
...you don't know if a value is a promise or not, promise.resolve(value) it instead and work with the return value as a promise. instance methods promise.prototype.catch() appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. promise.prototype.then() appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. ...
...the handler is called when the promise is settled, whether fulfilled or rejected. ...
WebAssembly.CompileError - JavaScript
the webassembly.compileerror object indicates an error during webassembly decoding or validation. constructor webassembly.compileerror() creates a new webassembly.compileerror object. instance properties webassembly.compileerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.compileerror.prototype.name error name. inherited from error. webassembly.compileerror.prototype.filename path to file that raised this error. inherited from error. webassembly.compileerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.compileerror.prototype.columnnumber column number in line that raised this error. inherit...
...inherited from error. ...
...inherited from error. ...
...inherited from error. ...
WebAssembly.LinkError - JavaScript
the webassembly.linkerror object indicates an error during module instantiation (besides traps from the start function). constructor webassembly.linkerror() creates a new webassembly.linkerror object. instance properties webassembly.linkerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.linkerror.prototype.name error name. inherited from error. webassembly.linkerror.prototype.filename path to file that raised this error. inherited from error. webassembly.linkerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.linkerror.prototype.columnnumber column number in line that raised this error. inher...
...inherited from error. ...
...inherited from error. ...
...inherited from error. ...
WebAssembly.RuntimeError - JavaScript
the webassembly.runtimeerror object is the error type that is thrown whenever webassembly specifies a trap. constructor webassembly.runtimeerror() creates a new webassembly.runtimeerror object. instance properties webassembly.runtimeerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.runtimeerror.prototype.name error name. inherited from error. ...
... webassembly.runtimeerror() creates a new webassembly.runtimeerror object. instance properties webassembly.runtimeerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.runtimeerror.prototype.name error name. inherited from error. webassembly.runtimeerror.prototype.filename path to file that raised this error. inherited from error. webassembly.runtimeerror.prototype.linenumber line number in file that raised this 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 ...
...inherited from error. ...
...inherited from error. ...
delete operator - JavaScript
page for more details. the delete operator removes a given property from an object. on successful deletion, it will return true, else false will be returned. however, it is important to consider the following scenarios: if the property which you are trying to delete does not exist, delete will not have any effect and will return true. if a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties). any property declared with var cannot be deleted from the global scope or from a function's scope. as such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression). fun...
...ram) { // syntaxerror in strict mode. console.log(delete param); // false } // syntaxerror in strict mode. console.log(delete func); // false cross-browser notes although ecmascript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). however, in the case of internet explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. in explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the...
...; // returns true // delete does not affect built-in static properties. delete math.pi; // returns false // employeedetails is a property of the global scope. // since it was defined without "var", it is marked configurable. delete employeedetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } delete and the prototype chain in the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: function foo() { this.bar = 10; } foo.prototype.bar = 42; var foo = new foo(); // foo.bar is associated with the // own property. console.log(foo.bar); // 10 // delete the own property within the // foo object. delete foo.bar; // returns true // ...
...delete an own property of an object while a property with the same name is available on the prototype chain: function foo() { this.bar = 10; } foo.prototype.bar = 42; var foo = new foo(); // foo.bar is associated with the // own property. console.log(foo.bar); // 10 // delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log(foo.bar); // 42 // delete the property on the prototype. delete foo.prototype.bar; // returns true // the "bar" property can no longer be // inherited from foo since it has been // deleted. console.log(foo.bar); // undefined deleting array elements when you delete an array element, the array length is not affected. this holds even if you delete the last element of the array...
new operator - JavaScript
define the object type by writing a function. create an instance of the object with new. to define an object type, create a function for the object type that specifies its name and properties. an object can have a property that is itself another object. see the examples below. when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype. the constructor function foo is called with the specified arguments, and with this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. the object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression. if the constructor func...
...iously defined object. for example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black". however, this does not affect any other objects. to add the new property to all objects of the same type, you must add the property to the definition of the car object type. you can add a shared property to a previously defined object type by using the function.prototype property. this defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1. for more information, see prototype. function car() {} car1 = new c...
...d with that function, rather than by just one instance of the object type. the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1. for more information, see prototype. ...
...r, and then overwrites that value with the string "black" only in the instance object car1. for more information, see prototype. function car() {} car1 = new car(); car2 = new car(); console.log(car1.color); // undefined car.prototype.color = 'original color'; console.log(car1.color); // 'original color' car1.color = 'black'; console.log(car1.color); // 'black' console.log(object.getprototypeof(car1).color); // 'original color' console.log(object.getprototypeof(car2).color); // 'original color' console.log(car1.color); // 'black' console.log(car2.color); // 'original color' if you didn't write the new operator, the constructor function would be invoked like any regular function, without creating an object. in this case, the value of this is also different. examples object ty...
this - JavaScript
ct. to set the value of this to a particular value when calling a function, use call(), or apply() as in the examples below. class context the behavior of this in classes and functions is similar, since classes are functions under the hood. but there are some differences and caveats. within a class constructor, this is a regular object. all non-static methods within the class are added to the prototype of this: class example { constructor() { const proto = object.getprototypeof(this); console.log(object.getownpropertynames(proto)); } first(){} second(){} static third(){} } new example(); // ['constructor', 'first', 'second'] note: static methods are not properties of this. they are properties of the class itself. derived classes unlike base class constructors, derived ...
...as this is 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 ar...
...diate member reference. in the following example, when we invoke the function, we call it as a method g of the object o.b. this time during execution, this inside the function will refer to o.b. the fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters. o.b = {g: independent, prop: 42}; console.log(o.b.g()); // 42 this on the object's prototype chain the same notion holds true for methods defined somewhere on the object's prototype chain. if the method is on an object's prototype chain, this refers to the object the method was called on, as if the method were on the object. var o = {f: function() { return this.a + this.b; }}; var p = object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5 in this example, the object assigned t...
...ject's prototype chain. if the method is on an object's prototype chain, this refers to the object the method was called on, as if the method were on the object. var o = {f: function() { return this.a + this.b; }}; var p = object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5 in this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. but it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. that is, since f is called as a method of p, its this refers to p. this is an interesting feature of javascript's prototype inheritance. this with a getter or setter again, the same notion ...
Preferences - Archive of obsolete content
{ // keeping a reference to the observed preference branch or it will get // garbage collected. ...
...ame); this._branch.queryinterface(components.interfaces.nsiprefbranch2); this._callback = callback; } preflistener.prototype.observe = function(subject, topic, data) { if (topic == 'nspref:changed') this._callback(this._branch, data); }; /** * @param {boolean=} trigger if true triggers the registered function * on registration, that is, when this method is called. */ preflistener.prototype.register = function(trigger) { this._branch.addobserver('', this, false); if (trigger) { let that = this; this._branch.getchildlist('', {}). ...
...f true triggers the registered function * on registration, that is, when this method is called. */ preflistener.prototype.register = function(trigger) { this._branch.addobserver('', this, false); if (trigger) { let that = this; this._branch.getchildlist('', {}). ...
Offering a context menu for form controls - Archive of obsolete content
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> change the right-click behavior the overlaid code is responsible for adjusting the behavior of right-clicking on form controls. ...
...cation/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> change the right-click behavior the overlaid code is responsible for adjusting the behavior of right-clicking on form controls. ...
...arget; components.utils.reporterror(settargetoriginal); nscontextmenu.prototype.settarget = function(anode, arangeparent, arangeoffset) { settargetoriginal.apply(this, arguments); if (this.istargetaformcontrol(anode)) this.shoulddisplay = true; }; }, false); this code, which is run when the window is opened up, works by replacing the settarget() routine for the prototype of nscontextmenu with one that forces the context menu to display if the target of the menu is a form control. as a result, all controls in the window will support a context menu when right-clicked, since we've changed the core behavior of context menus to override their default behavior of doing nothing on form controls. ...
Promises - Archive of obsolete content
// path, at 1000ms minimum intervals. this.saver = new deferredsave(this.path, () => json.stringify(this.data), 1000); return this; }.bind(this)); } /** * immediately save the data to disk. * * @return {promise} a promise which resolves when the file's contents * have been written. ...
...omise} a promise which resolves when the file's contents * have been written. */ jsonstore.prototype.flush = function () { return this.saver.flush(); }; /** * queue a save operation. the operation will commence after a full * second has passed without further calls to this method. * * @return {promise} a promise which resolves when the file's contents * have been written. ...
...mimetype) xhr.overridemimetype(params.options); xhr.open(options.method || defaultmethod, url); if (options.responsetype) xhr.responsetype = options.responsetype; for (let header of object.keys(options.headers || {})) xhr.setrequestheader(header, options.headers[header]); let data = options.data; if (data && object.getprototypeof(data).constructor.name == "object") { options.data = new formdata; for (let key of object.keys(data)) options.data.append(key, data[key]); } xhr.send(options.data); }); } example usage: task.spawn(function* () { let request = yield request("http://example.com/", { method: "put", mimetype: "application/json", ...
How to implement a custom XUL query processor component - Archive of obsolete content
?name=xxx", where the xxx is the querytype used in the xul template block. ...
...urn null; }, // called when a rule matches this item. ...
... function templatequeryprocessor() { // our basic list of data this._data = [ {name: "mark", age: 36, hair: "brown", eye: "brown"}, {name: "bill", age: 25, hair: "red", eye: "black"}, {name: "joe", age: 15, hair: "blond", eye: "blue"}, {name: "jimmy", age: 65, hair: "gray", eye: "dull"} ]; } templatequeryprocessor.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsixultemplatequeryprocessor]), classdescription: "sample xul template query processor", classid: components.id("{282cc4ea-a49c-44fc-81f4-1f03cbb7825f}"), contractid: "@mozilla.org/xul/xul-query-processor;1?name=simpledata", getdatasource: function(adatasources, arootnode, aistrusted, abuilder, ashoulddelaybuilding) { ...
Object-oriented JavaScript for beginners - Learn web development
1 and person2 variables contain the following objects: { name: 'bob', greeting: function() { alert('hi! i\'m ' + this.name + '.'); } } { name: 'sarah', greeting: function() { alert('hi! i\'m ' + this.name + '.'); } } note that when we are calling our constructor function, we are defining greeting() every time, which isn't ideal. to avoid this, we can define functions on the prototype instead, which we will look at later. creating our finished constructor the example we looked at above was only a simple example to get us started. let's now get on and create our final person() constructor function. remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity: ...
...n the next two articles, so you might want to read them first before you try the tests. summary this article has provided a simplified view of object-oriented theory — this isn't the whole story, but it gives you an idea of what we are dealing with here. ...
... view of object-oriented theory — this isn't the whole story, but it gives you an idea of what we are dealing with here. in addition, we have started to look at different ways of generating object instances. in the next article, we'll explore javascript object prototypes. ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
app. editing the name of a task we don’t have a user interface for editing the name of a task yet. we'll get to that in a moment. to start with, we can at least implement an edittask() function in app.js. it’ll be similar to deletetask() because it'll take an id to find its target object, but it'll also take a newname property containing the name to update the task to. we'll use array.prototype.map() instead of array.prototype.filter() because we want to return a new array with some changes, instead of deleting something from the array. add the edittask() function inside your app component, in the same place as the other functions: function edittask(id, newname) { const editedtasklist = tasks.map(task => { // if this task has the same id as the edited task if (id === task.id) ...
...n't actually filter the todos in the ui! let's finish this off. filtering tasks in the ui right now, our tasklist constant in app() maps over the tasks state and returns a new <todo /> component for all of them. this is not what we want! a task should only render if it is included in the results of applying the selected filter. before we map over the tasks state, we should filter it (with array.prototype.filter()) to eliminate objects we don't want to render. update your tasklist like so: const tasklist = tasks .filter(filter_map[filter]) .map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask={deletetask} edittask={edittask} /> )); in order to decide...
...want to render. update your tasklist like so: const tasklist = tasks .filter(filter_map[filter]) .map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask={deletetask} edittask={edittask} /> )); in order to decide which callback function to use in array.prototype.filter(), we access the value in filter_map that corresponds to the key of our filter state. when filter is all, for example, filter_map[filter] will evaluate to () => true. choosing a filter in your browser will now remove the tasks that do not meet its criteria. the count in the heading above the list will also change to reflect the list! summary so that's it — our app is now functionall...
Displaying Places information using views
treeview"); treeview.selectplaceuri("some place uri"); to select a row in the tree that contains a specific nsinavhistoryresultnode: var treeview = document.getelementbyid("myplacestreeview"); treeview.selectnode(somehistoryresultnode); placestreeview note: this section describes the implementation of the places tree view. the built-in tree view is backed by an instance of placestreeview, a prototype defined in browser/components/places/content/treeview.js. placestreeview performs double duty for the built-in tree view: it implements both nsitreeview and much of the functionality required of a places view. the latter functionality is specified specifically by interface nsinavhistoryresulttreeviewer, which inherits from the more general nsinavhistoryresultobserver . because of placestreeview'...
...ook at using the tree view above to get an idea of what's required. custom nsitreeviews in general are a lot of work, and if you are not familiar with creating custom nsitreeviews, see the custom tree views and tree view details pages in the xul tutorial. all of that information is relevant here. fortunately you can commandeer parts of the built-in tree view to suit your purposes. the javascript prototype backing the built-in view, placestreeview, is especially useful since it implements all three of nsinavhistoryresulttreeviewer, nsinavhistoryresultobserver, and nsitreeview. you can therefore implement your own custom functionality on top of placestreeview while relying on it for non-custom functionality and much of the tedious work. one strategy is to create your custom object(s) implementing ea...
...nvenience properties or methods of the built-in places tree view. if your custom view is used only once in your application, code similar to the above will likely be sufficient; it's enough to create a single placestreeview object, modify it, and attach it to a regular tree. if your view is widely used, however, you may want to take a cue from the built-in tree view and create your own javascript prototype similar to placestreeview and your own xbl tree binding so that much of the work of creating views and viewers and hooking them up to results is abstracted away. the attribute nsinavhistoryresultnode.viewindex is provided explicitly for the use of the view. this value is initialized to -1 when each node is created. you can use this value to keep track of visible nodes. placestreeview uses this a...
NSS API Guidelines
pulled. if you're good with tagging your releases, and then checking out (or exporting!) from the tag for your build, this saves you from messing around with specific files revision numbers. header files we have a preferred naming system for include files. we had been moving towards one, for some time, but for the nss 3.0 project we finally wrote it down. data types function prototypes public nss____t.h nss____.h friend (only if required) nss____tf.h nss____f.h nss-private ____t.h ____.h module-private ____tm.h ____m.h the files on the right include the files to their left; the files in a row include the files directly above them. header files always include what they need; the files are protected against doubl...
...r). note: it's not necessary all eight files exist. further, this is a simple ideal, and often reality is more complex. we would like to keep names to 8.3, even if we no longer support win16. this usually gives us four characters to identify a module of nss. in short: header files for consumption outside nss start with "nss." header files with types have a trailing "t", header files with prototypes don't. "extern" declarations of data also go in the prototypes files. "friend" headers are for things that we really wish weren't used by non-nss code, but which are. those files have a trailing "f," and their use should be deprecated. "module" headers are for things used only within a specific subset of nss; things which would have been "static" if we had combined separate c source files toge...
...doing. note: error stacks are vertical, and never horizontal. if multiple things go wrong simultaneously, and you want to report them all, use another mechanism. errors, though not integers, are done as external constants, instead of preprocessor definitions. this is so any additional error doesn't trigger the entire tree to rebuild. likewise, the external references to errors are made in the prototypes files, with the functions which can return them. error stacks are thread-private. the usual semantic is that public routines clear the stack first, private routines don't. usually, every public routine has a private counterpart, and the implementation of the public routine looks like this: nssimplement rv * nsstype_method ( nsstype *t, nssfoo *arg1, nssbar ...
Rhino serialization
scenes when rhino serializes objects. how rhino serialization works by default, java serialization of an object also serializes objects that are referred to by that object. upon deserialization the initial object and the objects it refers to are all created and the references between the objects are resolved. however, for javascript this creates a problem. ...
...hat are referred to by that object. upon deserialization the initial object and the objects it refers to are all created and the references between the objects are resolved. however, for javascript this creates a problem. javascript objects contain references to prototypes and to parent scopes. default serialization would serialize the object or function we desired but would also serialize object.prototype or even possibly the entire top-level scope and everything it refers to! we want to be able to serialize a javascript object and then deserialize it into a new scope and have all of the references from the deserialized object to prototypes and parent scopes resolved correctly to refer to objects in the new scope. scriptableoutputstream takes a scope as a parameter to its constructor. if in the pr...
...ion. use the addexcludedname method of scriptableoutputstream to add new names. by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects. if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization. exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputstream or scriptableinputstream. rhino serialization in compilation mode serialization works well wit...
Self-hosted builtins in SpiderMonkey
he global object. self-hosted code has access to some functionality that's not available to normal js code. most importantly, it's possible to invoke any function within the scope of any object using the syntax callfunction(fun, receiver, ...args) (or callcontentfunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments. in contrast to function.prototype.call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation. otoh, normal method calls are forbidden in self-hosted code. so instead of receiver.fun(arg1, ..., argn) you have to use callfunction(fun, receiver, arg1, ... argn). this restriction was added because otherwise it's extremely eas...
... functions when assuming that content can't interfere with behavior. e.g., if receiver is an object that content has access to, then callfunction(receiver.fun, receiver) wouldn't be guaranteed to work, because content might have changed the value of receiver.fun, so callcontentfunction(receiver.fun, receiver) has to be used. self-hosted functions by default are not constructors and do not have a prototype property, so that they meet the requirements for standard built-in functions as described in the ecmascript language specification 5.1, clause 15. to make a self-hosted function a constructor, call makeconstructible(functionname) after the function declaration. a prototype property can be added from the self-hosted code itself. all self-hosted functions have direct access to each other and can r...
...a select set of c++-implemented builtins is installed via the intrinsic_functions array in selfhosting.cpp, as described below. using the same mechanism, c++-implemented helper functions are made available to self-hosted code. ...
JIT Optimization Outcomes
because somehow the property was accessed in a way that returned a different type than the expected constant. this is an unlikely failure mode, and should not occur. indictionarymode the object whose property is being accessed is in dictionary mode. objects which are used in ways that suggest they are hashtables are turned into dictionary objects and their types marked as such. noprotofound a prototype object was not found for all the object used by this operation. multiprotopaths objects used in this operation had differing prototypes. nonwritableproperty the property being assigned to is not writable for some types of objects which are used in this operation. protoindexedprops the object being accessed has indexed properties that are exotic (for example, defined as a property on a proto...
...function could not be compiled by the baseline compiler. cantinlinelazy unable to inline function call. the interpreted callee function has a lazy, compiled on-demand script instead of an already compiled script. cantinlinenotconstructor unable to inline function call. rare. the interpreted callee function is invoked with new but cannot be called as a constructor. property accessors, function.prototype, and arrow (=>) functions cannot be called as constructors. cantinlinedisableion unable to inline function call. the interpreted callee function has been explicitly blacklisted against ion compilation. cantinlinetoomanyargs unable to inline function call. the interpreted callee function either has too many parameters or is called with too many arguments. these thresholds are subject to change...
.... the engine knows nothing definite about the type of the callee function object. cantinlineunreachable unable to inline function call. the call site has not been observed to have ever been executed. it lacks observed type information for its arguments, its return value, or both. cantinlinebound unable to inline function call. the interpreted callee is a bound function generated from function.prototype.bind that failed some sub-checks. (expand) cantinlinenativenospecialization unable to inline function call. ion does not have built-in specialization for the native (implemented in c++) callee function. cantinlinenativebadform unable to inline function call. the native callee function was called with an unsupported number of arguments, or calling non-constructing functions with new. cantinli...
JS_NewObjectForConstructor
pi 14 name type description cx jscontext * the context in which to create the new object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp const jsclass * the class of the object to create. added in spidermonkey 17 vp jsval * pointer to a constructor. this must be an object that has a prototype property. args js::callargs &amp; call argument to get a constructor as callee. added in spidermonkey 38 description js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this fun...
... constructor as callee. added in spidermonkey 38 description js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this function will assert (in debug builds). ...
...th new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this function will assert (in debug builds). if the constructor does not have a prototype property, this function will return null and set an exception on cx. the standard object creation api, js_newobject, takes explicit arguments for the class, prototype, and parent of the new object. with js_newobjectforconstructor, the prototype and parent are determined by the constructor, and class is still determined by the caller. the prototype is the prototype of the constructor if it is an object, otherwise null. the parent is the constructor's parent. see also mxr id search for js_newobjectforconstructor js_newobject object_to_jsval bug 581263 - added ...
Components.utils.Sandbox
org/nullprincipal;1"].createinstance(ci.nsiprincipal); from firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument. options the constructor accepts an optional parameter. this parameter is an object with the following optional properties: freshzone if true creates a new gc region separate from both the calling context's and the sandbox prototype's region. addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use samezoneas instead. samezoneas a javascript object in whose garbage collection region the sandbox should be created in. this helps to improve memory usage by allowing sandboxes to be discarded when that zone goes away. content scripts should pass the window they're running ...
...ces in the future). this property is optional, but very useful for tracking memory usage of add-ons and other javascript compartments. a recommended value for this property is an absolute path to the script responsible for creating the sandbox. as of gecko 13 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), if you don't specify a sandbox name it will default to the caller's filename. sandboxprototype a prototype object for the sandbox. the sandbox will inherit the contents of this object if it's provided. passing a content window object, setting wantxrays:true (default) and using an extended principal provides a clean, isolated execution environment in which javascript code that needs web apis (such as accessing the window's dom) can be executed without interference from untrusted conten...
... sandbox to be freed immediately. example executing in current tab scope more ways to load scripts into a sandbox can be found on the loading scripts page. this example is to be run from scratchpad with environemnt set to browser. it alerts the dollar sign function. this code was tested on twitter.com and gets access to the jquery $. var sandboxscript = 'alert($)'; var options = { sandboxprototype: content, wantxrays: false // only set this to false if you need direct access to the page's javascript. true provides a safer, isolated context. }; var sandbox = cu.sandbox(content, options); cu.evalinsandbox(sandboxscript, sandbox); cu.nukesandbox(sandbox); ...
Debugger.Memory - Firefox Developer Tools
memory.maxallocationsloglength. censuses a census is a complete traversal of the graph of all reachable memory items belonging to a particular debugger‘s debuggees. it produces a count of those items, broken down by various criteria. ifdbg is a debugger instance, you can call dbg.memory.takecensus to conduct a census of its debuggees’ possessions. accessor properties of the debugger.memory.prototype object ifdbg is a debugger instance, then <i>dbg</i>.memory is a debugger.memory instance, which inherits the following accessor properties from its prototype: trackingallocationsites a boolean value indicating whether this debugger.memory instance is capturing the javascript execution stack when each object is allocated. this accessor property has both a getter and setter: assigning to it...
...es the allocation site tracking. reading the accessor produces true if the debugger is capturing stacks for object allocations, and false otherwise. allocation site tracking is initially disabled in a new debugger. assignment is fallible: if the debugger cannot track allocation sites, it throws an error instance. you can retrieve the allocation site for a given object with the debugger.object.prototype.allocationsite accessor property. allocationsamplingprobability a number between 0 and 1 that indicates the probability with which each new allocation should be entered into the allocations log. 0 is equivalent to “never”, 1 is “always”, and .05 would be “one out of twenty”. the default is 1, or logging every allocation. note that in the presence of multiple debugger instanc...
...ll gc was necessary. otherwise, null is returned. known values include the following: “gc mode” “malloc bytes trigger” “allocation trigger” “requested” gccyclenumber the gc cycle’s “number”. does not correspond to the number of gc cycles that have run, but is guaranteed to be monotonically increasing. function properties of the debugger.memory.prototype object memory use analysis exposes implementation details memory analysis may yield surprising results, because browser implementation details that are transparent to content javascript often have visible effects on memory consumption. web developers need to know their pages’ actual memory consumption on real browsers, so it is correct for the tool to expose these behaviors, as long as it i...
Debugger.Script - Firefox Developer Tools
vior of the property or method differs between the instance referring to a jsscript or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to a jsscript” and “if the instance refers to webassembly code”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor properties of the debugger.script prototype object a debugger.script instance inherits the following accessor properties from its prototype: isgeneratorfunction true if this instance refers to a jsscript for a function defined with a function* expression or statement. false otherwise. isasyncfunction true if this instance refers to a jsscript for an async function, defined with an async function expression or statement. false otherw...
...ebassembly code, throw a typeerror. url if the instance refers to a jsscript, the filename or url from which this script’s code was loaded. for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url. for function.prototype’s script, this is null. if this debugger.script’s source property is non-null, then this is equal to source.url. if the instance refers to webassembly code, throw a typeerror. startline if the instance refers to a jsscript, the number of the line at which this script’s code starts, within the file or document named by url. linecount if the instance refers to a jsscript, the number o...
...e referring to the global object in whose scope this script runs. the result refers to the global directly, not via a wrapper or a windowproxy (“outer window”, in firefox). if the instance refers to webassembly code, throw a typeerror. format if the instance refers to a jsscript, "js". if the instance refers to webassembly code, "wasm". function properties of the debugger.script prototype object the functions described below may only be called with a this value referring to a debugger.script instance; they may not be used as methods of other kinds of objects. getalloffsets() if the instance refers to a jsscript, return an arrayl describing the relationship between bytecode instruction offsets and source code positions in this script.l is sparse, and indexed by source line n...
Debugger.Source - Firefox Developer Tools
operty or method differs between the instance referring to javascript source or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to javascript source” and “if the instance refers to webassembly code”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor properties of the debugger.source prototype object a debugger.source instance inherits the following accessor properties from its prototype: text if the instance refers to javascript source, the javascript source code, as a string. the value satisfies the program, functiondeclaration, or functionexpression productions in the ecmascript standard. if the instance refers to webassembly code, the serialized text representation. the fo...
...ains the webassembly bytecode. url if the instance refers to javascript source, the filename or url from which this script’s code was loaded. for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url. for function.prototype’s script, this is null. source may be loaded from a url in the following ways: the url may appear as the src attribute of a <script> element in markup text. the url may be passed to the worker web worker constructor, or the web worker importscripts function. the url may be the name of a xpcom javascript module or subscript. (note that code passed to eval, the f...
...ibute, this is the name of that attribute, a string. otherwise, this is undefined. introductiontype if the instance refers to javascript source, a string indicating how this source code was introduced into the system. this accessor returns one of the following values: "eval", for code passed to eval. "function", for code passed to the function constructor. "function.prototype", for function.prototype internally generated code. "worker", for code loaded by calling the web worker constructor—the worker’s main script. "importscripts", for code by calling importscripts in a web worker. "eventhandler", for code assigned to dom elements’ event handler idl attributes as a string. "scriptelement", for code belonging to <script> elemen...
Blob - Web APIs
Web › API › Blob
set of another blob's data, use the slice() method. to obtain a blob object for a file on the user's file system, see the file documentation. the apis accepting blob objects are also listed in the file documentation. constructor blob() returns a newly created blob object which contains a concatenation of all of the data in the array passed into the constructor. instance properties blob.prototype.size read only the size, in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. instance methods blob.prototype.arraybuffer() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data. blob.pro...
...he mime type of the data contained in the blob. if the type is unknown, this string is empty. instance methods blob.prototype.arraybuffer() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data. blob.prototype.slice() returns a new blob object containing the data in the specified range of bytes of the blob on which it's called. blob.prototype.stream() returns a readablestream that can be used to read the contents of the blob. blob.prototype.text() returns a promise that resolves with a usvstring containing the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() constructor can create blobs from other objects. for example, to construct a blob from a json string: const obj = {hello: 'world'...
...tent of a blob as a typed array: const reader = new filereader(); reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to use a response. the following code reads the content of a blob as text: const text = await (new response(blob)).text(); or by using blob.prototype.text(): const text = await blob.text(); by using other methods of filereader, it is possible to read the contents of a blob as a string or a data url. specifications specification status comment file apithe definition of 'the blob interface' in that specification. working draft initial definition. ...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
living standard initial definition. ...
... living standard initial definition. ...
... living standard initial definition. ...
Element.closest() - Web APIs
Web › API › Element › closest
> div"); // returns the closest ancestor which is a div and has a parent article, here it is the div-01 var r4 = el.closest(":not(div)"); // returns the closest ancestor which is not a div, here it is the outmost article polyfill for browsers that do not support element.closest(), but carry support for element.matches() (or a prefixed equivalent, meaning ie9+), a polyfill exists: if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatchesselector || element.prototype.webkitmatchesselector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); re...
... return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually. however, it will only support css 2.1 selectors in ie 8, and it can cause severe lag spikes in production websites. ...
...telement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually. however, it will only support css 2.1 selectors in ie 8, and it can cause severe lag spikes in production websites. ...
EventTarget - Web APIs
in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. ...
...ludes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. ...
... handler) eventhandler geteventhandler(domstring type) example simple implementation of eventtarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = null; eventtarget.prototype.addeventlistener = function(type, callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(callback); }; eventtarget.prototype.removeeventlistener = function(type, callback) { if (!(type in this.listeners)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback){ stack.splice(i, 1); return; } } }; eventtarget.prototype.dispatchevent = function(event) { if (!(event.type in this.listeners)) { return true; } var sta...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
e following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("nextelementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "nextelementsibling", { get: function(){ var e = this.nextsibling; while(e && 1 !== e.nodetype) e = e.nextsibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/nextelementsibling/nextelementsibling.md (function (arr) { ...
... living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the new inter...
... living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the new interface. element tr...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
s: siblings of div-03 1. li 2. li 3. div 4. ...
... living standard splitted the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces im...
... living standard splitted the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the new interfa...
ParentNode.childElementCount - Web APIs
representing a document, documentfragment, or element. example var foo = document.getelementbyid('foo'); if (foo.childelementcount > 0) { // do something } polyfill for ie8 & ie9 & safari this property is completely unsupported prior to ie9. in ie9 and safari, it is unsupported in the document and documentfragment objects. ...
...entfragment, or element. example var foo = document.getelementbyid('foo'); if (foo.childelementcount > 0) { // do something } polyfill for ie8 & ie9 & safari this property is completely unsupported prior to ie9. in ie9 and safari, it is unsupported in the document and documentfragment objects. ...
... if (foo.childelementcount > 0) { // do something } polyfill for ie8 & ie9 & safari this property is completely unsupported prior to ie9. in ie9 and safari, it is unsupported in the document and documentfragment objects. ...
XMLHttpRequest.sendAsBinary() - Web APIs
can create the binary string using the filereader method readasbinarystring(). the string is converted to binary for transfer by removing the high-order byte of each character. return value undefined. polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arrays. ...
...igh-order byte of each character. return value undefined. polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arrays. ...
...value undefined. polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arrays. ...
About JavaScript - JavaScript
what is javascript? javascript® (often shortened to js) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for web pages, but it's used in many non-browser environments as well. it is a prototype-based, multi-paradigm scripting language that is dynamic, and supports object-oriented, imperative, and functional programming styles. javascript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. javascript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior. contrary to popular misconception, javascript is not "interpreted java". in a nutshell, javascript is a dynamic scripting language supporti...
...javascript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. javascript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior. contrary to popular misconception, javascript is not "interpreted java". in a nutshell, javascript is a dynamic scripting language supporting prototype based object construction. the basic syntax is intentionally similar to both java and c++ to reduce the number of new concepts required to learn the language. language constructs, such as if statements, for and while loops, and switch and try ... catch blocks function the same as in these languages (or nearly so). javascript can function as both a procedural and an object oriented language. obje...
...se languages (or nearly so). javascript can function as both a procedural and an object oriented language. objects are created programmatically in javascript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like c++ and java. once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects. javascript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval), object introspection (via for ... in), and source code recovery (javascript programs can decompile function bodies back into their source text). for a more in depth discussion of javascript programming follow the ...
Closures - JavaScript
p(text.help); } }); } setuphelp(); performance considerations it is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed 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). consider the following case: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); this.getname = function() { return this.name; }; this.getmessage = function() {...
... 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. 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.na...
...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. ...
Indexed collections - JavaScript
ot share all of their methods. the arguments object provides a length attribute but does not implement the foreach() method, for example. array methods cannot be called directly on array-like objects. ...
...vides a length attribute but does not implement the foreach() method, for example. array methods cannot be called directly on array-like objects. function printarguments() { arguments.foreach(function(item) { // typeerror: arguments.foreach is not a function console.log(item); }); } but you can call them indirectly using function.prototype.call(). ...
...methods cannot be called directly on array-like objects. function printarguments() { arguments.foreach(function(item) { // typeerror: arguments.foreach is not a function console.log(item); }); } but you can call them indirectly using function.prototype.call(). function printarguments() { array.prototype.foreach.call(arguments, function(item) { console.log(item); }); } array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays: array.prototype.foreach.call('a string', function(chr) { console.log(chr) }) typed arrays javascript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. as you already know, array objects grow and shrink dynamically and can have ...
JavaScript error reference - JavaScript
uality (==) mistyped as assignment (=)?syntaxerror: unterminated string literaltypeerror: "x" has no propertiestypeerror: "x" is (not) "y"typeerror: "x" is not a constructortypeerror: "x" is not a functiontypeerror: "x" is not a non-null objecttypeerror: "x" is read-onlytypeerror: 'x' is not iterabletypeerror: more arguments neededtypeerror: reduce of empty array with no initial valuetypeerror: x.prototype.y called on incompatible typetypeerror: can't access dead objecttypeerror: can't access property "x" of "y"typeerror: can't assign to property "x" on "y": not an objecttypeerror: can't define property "x": "obj" is not extensibletypeerror: can't delete non-configurable array elementtypeerror: can't redefine non-configurable property "x"typeerror: cannot use "in" operator to search for "x" in "y"t...
... "x" of "y"typeerror: can't assign to property "x" on "y": not an objecttypeerror: can't define property "x": "obj" is not extensibletypeerror: can't delete non-configurable array elementtypeerror: can't redefine non-configurable property "x"typeerror: cannot use "in" operator to search for "x" in "y"typeerror: cyclic object valuetypeerror: invalid "instanceof" operand "x"typeerror: invalid array.prototype.sort argumenttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarn...
...menttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
The arguments object - JavaScript
em as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = 'new value'; the arguments object is not an array. it is similar, but lacks all array properties except length. for example, it does not have the pop() method. ...
...iterator] returns a new array iterator object that contains the values for each index in arguments. examples defining a function that concatenates several strings this example defines a function that concatenates several strings. the function's only formal argument is a string containing the characters that separate the items to concatenate. function myconcat(separator) { let args = array.prototype.slice.call(arguments, 1); return args.join(separator); } you can pass as many arguments as you like to this function. it returns a string list using each argument in the list: // returns "red, orange, blue" myconcat(', ', 'red', 'orange', 'blue'); // returns "elephant; giraffe; lion; cheetah" myconcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah'); // returns "sage. basil. oregano. pepper.
... defining a function that creates html lists this example defines a function that creates a string containing html for a list. the only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). the function is defined as follows: function list(type) { var html = '<' + type + 'l><li>'; var args = array.prototype.slice.call(arguments, 1); html += args.join('</li><li>'); html += '</li></' + type + 'l>'; // end list return html; } you can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. for example: let listhtml = list('u', 'one', 'two', 'three'); /* listhtml is: "<ul><li>one</li><li>two</li><li>three</li></ul>" */ rest, defau...
Array.isArray() - JavaScript
ed; otherwise, 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. ...
...it's not natively available. ...
...{ array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(undefined); array.isarray(17); array.isarray('array'); array.isarray(true); array.isarray(false); array.isarray(new uint8array(32)); array.isarray({ __proto__: array.prototype }); instanceof vs isarray when checking for array instance, array.isarray is preferred over instanceof because...
BigInt - JavaScript
12n 0n && 12n // ↪ 0n boolean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a new bigint value. static 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. overrid...
... usage recommendations coercion because coercing between number and bigint can lead to loss of precision, it is recommended to only use bigint when values greater than 253 are reasonably expected and not to coerce between the two types. ...
...easonably expected and not to coerce between 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.Collator - JavaScript
ve examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.collator() creates a new collator object. static methods intl.collator.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.collator.prototype.compare getter function that compares two strings according to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. examples using collator the following example demonstrates the different potential results for a string occurring b...
...('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-specific. that is, the specification requires only that the before and after values are negative and positive. using locales the results provided by collator.prototype.compare() vary between languages. in order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // in german, ä sorts with a console.log(new intl.collator('de').compare('ä', 'z')); // → a negative value // in swedish, ä sorts after z console.log(new intl.co...
... of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // in german, ä sorts with a console.log(new intl.collator('de').compare('ä', 'z')); // → a negative value // in swedish, ä sorts after z console.log(new intl.collator('sv').compare('ä', 'z')); // → a positive value using options the results provided by collator.prototype.compare() can be customized using the options argument: // in german, ä has a as the base letter console.log(new intl.collator('de', { sensitivity: 'base' }).compare('ä', 'a')); // → 0 // in swedish, ä and a are separate base letters console.log(new intl.collator('sv', { sensitivity: 'base' }).compare('ä', 'a')); // → a positive value specifications specification ec...
Number - JavaScript
in javascript (-(253 - 1)). number.min_value the smallest positive representable number—that is, the positive number closest to zero (without actually being zero). number.nan special "not a number" value. number.negative_infinity special value representing negative infinity. returned on overflow. number.positive_infinity special value representing infinity. returned on overflow. number.prototype allows the addition of properties to the number object. static methods number.isnan() determine whether the passed value is nan. number.isfinite() determine whether the passed value is a finite number. number.isinteger() determine whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1)...
...ite number. number.isinteger() determine whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). number.parsefloat(string) this is the same as the global parsefloat() function. number.parseint(string, [radix]) this is the same as the global parseint() function. instance methods number.prototype.toexponential(fractiondigits) returns a string representing the number in exponential notation. number.prototype.tofixed(digits) returns a string representing 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.protot...
... string representing 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 ob...
Object.assign() - JavaScript
key. later sources' properties overwrite earlier ones. the object.assign() method only copies enumerable and own properties from a source object to a target object. it uses [[get]] on the source and [[set]] on the target, so it will invoke getters and setters. therefore it assigns properties, versus copying or defining new properties. this may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. for copying property definitions (including their enumerability) into prototypes, use object.getownpropertydescriptor() and object.defineproperty() instead. both string and symbol properties are copied. in case of an error, for example if a property is non-writable, a typeerror is raised, and the target object is changed if any properties are added before ...
...ow new typeerror('cannot convert undefined or null to object'); } var to = object(target); for (var index = 1; index < arguments.length; index++) { var nextsource = arguments[index]; if (nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.prototype.hasownproperty.call(nextsource, nextkey)) { to[nextkey] = nextsource[nextkey]; } } } } return to; }, writable: true, configurable: true }); } examples cloning an object const obj = { a: 1 }; const copy = object.assign({}, obj); console.log(copy); // { a: 1 } warning for deep clone for deep cloning, we need to use alterna...
... c: 3 } the properties are overwritten by other objects that have the same properties later in the parameters order. copying symbol-typed properties const o1 = { a: 1 }; const o2 = { [symbol('foo')]: 2 }; const obj = object.assign({}, o1, o2); console.log(obj); // { a : 1, [symbol("foo")]: 2 } (cf. bug 1207182 on firefox) object.getownpropertysymbols(obj); // [symbol(foo)] properties on the prototype chain and non-enumerable properties cannot be copied const obj = object.create({ foo: 1 }, { // foo is on obj's prototype chain. bar: { value: 2 // bar is a non-enumerable property. }, baz: { value: 3, enumerable: true // baz is an own enumerable property. } }); const copy = object.assign({}, obj); console.log(copy); // { baz: 3 } primitives will be wrapped to objects c...
Object.getOwnPropertyDescriptors() - JavaScript
le true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...as the object.assign() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and object.create() for a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. this can get awkward especially for getters and setters. ...
...etween two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. this can get awkward especially for getters and setters. instead, you can use this code to set the prototype: function superclass() {} superclass.prototype = { // define your methods and properties here }; function subclass() {} subclass.prototype = object.create( superclass.prototype, { // define your methods and properties here } ); specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptors' in that specification. ...
RangeError - JavaScript
the rangeerror object indicates an error when a value is not in the set or range of allowed values. description a rangeerror is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value. this can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor rangeerror() creates a new rangeerror object. instance properties rangeerror.prototype.message error message. although ecma-262 specifies that rangeerror should provide its o...
...r when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor rangeerror() creates a new rangeerror object. instance properties rangeerror.prototype.message error message. although ecma-262 specifies that rangeerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. rangeerror.prototype.name error name. inherited from error. rangeerror.prototype.filename path to file that raised this error. inherited from error. rangeerror.prototype.linenumber line number in file that raised this error. inherited from error. rangeerror.prototype.columnnumber column number in line that raised this error. ...
...inherited from error. ...
Reflect - JavaScript
es the following static functions which have the same names as the proxy handler methods. some of these methods are also the same as corresponding methods on object, although they do have some subtle differences between them. static methods reflect.apply(target, thisargument, argumentslist) calls a target function with arguments as specified by the argumentslist parameter. see also function.prototype.apply(). reflect.construct(target, argumentslist[, newtarget]) the new operator as a function. equivalent to calling new target(...argumentslist). also provides the option to specify a different prototype. reflect.defineproperty(target, propertykey, attributes) similar to object.defineproperty(). returns a boolean that is true if the property was successfully defined. reflect.deleteproperty(...
...arget[propertykey]. reflect.get(target, propertykey[, receiver]) returns the value of the property. works like getting a property from an object (target[propertykey]) as a function. reflect.getownpropertydescriptor(target, propertykey) similar to object.getownpropertydescriptor(). returns a property descriptor of the given property if it exists on the object, undefined otherwise. reflect.getprototypeof(target) same as object.getprototypeof(). reflect.has(target, propertykey) returns a boolean indicating whether the target has the property. either as own or inherited. works like the in operator as a function. reflect.isextensible(target) same as object.isextensible(). returns a boolean that is true if the target is extensible. reflect.ownkeys(target) returns an array of the target objec...
...wnkeys(target) returns an array of the target object's own (not inherited) property keys. reflect.preventextensions(target) similar to object.preventextensions(). returns a boolean that is true if the update was successful. reflect.set(target, propertykey, value[, receiver]) a function that assigns values to properties. returns a boolean that is true if the update was successful. reflect.setprototypeof(target, prototype) a function that sets the prototype of an object. returns a boolean that is true if the update was successful. examples detecting whether an object contains certain properties const duck = { name: 'maurice', color: 'white', greeting: function() { console.log(`quaaaack! my name is ${this.name}`); } } reflect.has(duck, 'color'); // true reflect.has(duck, 'hairc...
Symbol.matchAll - JavaScript
the symbol.matchall well-known symbol returns an iterator, that yields matches of the regular expression against a string. this function is called by the string.prototype.matchall() 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. description this symbol is used for string.prototype.matchall() and specifically in regexp.prototype[@@matchall](). the following two examples return same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses. property attributes of symbol.matchall writable no ...
... specifications specification ecmascript (ecma-262)the definition of 'symbol.matchall' in that specification. ...
... specifications specification ecmascript (ecma-262)the definition of 'symbol.matchall' in that specification. ...
Symbol.search - JavaScript
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. ...
... 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. ...
... 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. ...
TypeError - JavaScript
e is not of the expected type. a typeerror may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or when attempting to modify a value that cannot be changed; or when attempting to use a value in an inappropriate way. constructor typeerror() creates a new typeerror object. instance properties typeerror.prototype.message error message. although ecma-262 specifies that typeerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. typeerror.prototype.name error name. inherited from error. typeerror.prototype.filename path to file that raised this error. inherited from error. typeerror.prototype.linenumber line number in file that raised this error. inherited...
...inherited from error. ...
...inherited from error. ...
WebAssembly.Global - JavaScript
a webassembly.global object represents a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances. this allows dynamic linking of multiple modules. constructor webassembly.global() creates a new global object. ...
...e from both javascript and importable/exportable across one or more webassembly.module instances. this allows dynamic linking of multiple modules. constructor 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...
... examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor. ...
in operator - JavaScript
examples basic usage the following examples show some uses of the in operator. ...
...his 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 prop in object parameters prop a string or symbol representing a property name or array index (non-symbols will be coerced to strings). object object to check if it (or its prototype chain) contains the property with specified name (prop). examples basic usage the following examples show some uses of the in operator. // arrays let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'] 0 in trees // returns true 3 in trees // returns true 6 in trees // returns false 'bay' in trees // returns false (you must specify the index number, not the value at t...
...ing it directly returns undefined. let empties = new array(3) empties[2] // returns undefined 2 in empties // returns false 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. ...
JavaScript typed arrays - JavaScript
xample. typed array views are in the native byte-order (see endianness) of your platform. with a dataview you are able to control the byte-order. it is big-endian by default and can be set to little-endian in the getter/setter methods. web apis using typed arrays these are some examples of apis that make use of typed arrays; there are others, and more are being added all the time. filereader.prototype.readasarraybuffer() the filereader.prototype.readasarraybuffer() method starts reading the contents of the specified blob or file. xmlhttprequest.prototype.send() xmlhttprequest instances' send() method now supports typed arrays and arraybuffer objects as argument. imagedata.data is a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer v...
...oat32array(buffer, 20, 1); then you can access, for example, the amount due with amountdueview[0]. note: the data structure alignment in a c structure is platform-dependent. take precautions and considerations for these padding differences. conversion to normal arrays after processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the array prototype. ...
...ecautions and considerations for these padding differences. conversion to normal arrays after processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the array prototype. this can be done using array.from(), or using the following code where array.from() is unsupported. let typedarray = new uint8array([1, 2, 3, 4]), normalarray = array.prototype.slice.call(typedarray); normalarray.length === 4; normalarray.constructor === array; specifications specification ecmascript (ecma-262)the definition of 'typedarray objects' in that specification. ...
Example - SVG: Scalable Vector Graphics
at. this.x = rand( width ); this.y = rand( height ); // nil initial velocity. this.vx = this.vy = 0; // a visual element---initially none this.elt = null; } // turn this into a class. new mote(); // mote::applyforce() -- adjust velocity // towards the given position. // warning: pseudo-physics -- not really // governed by any /real/ physical principles. ...
...-physics -- not really // governed by any /real/ physical principles. mote.prototype.applyforce = function(pos, mag) { if( pos[0] > this.x ) this.vx += mag; else if( pos[0] < this.x ) this.vx -= mag; if( pos[1] > this.y ) this.vy += mag; else if( pos[1] < this.y ) this.vy -= mag; } // mote::capvelocity() -- apply an upper limit // on mote velocity. ...
...locity. mote.prototype.capvelocity = function() { var max = parseint( document.getelementbyid('max_velocity').value ); if( max < this.vx ) this.vx = max; else if( -max > this.vx ) this.vx = -max; if( max < this.vy ) this.vy = max; else if( -max > this.vy ) this.vy = -max; } // mote::capposition() -- apply an upper/lower limit // on mote position. mote.prototype.capposition = function() { var dims = dimensions(); if( this.x < 0 ) this.x = 0; else if( this.x >= dims[0] ) this.x = dims[0]-1; if( this.y < 0 ) this.y = 0; else if( this.y >= dims[1] ) this.y = dims[1]-1; } // mote::move() -- move a mote, update the screen. mote.prototype.move = function() { // apply attraction to cursor. var attract = parseint(...
/loader - Archive of obsolete content
the sandbox() function is a utility function for creating js sandboxes. it is used by the loader to create scopes into which modules are loaded. it takes the following set of configuration options: name: a string value which identifies the sandbox in about:memory. will throw exception if omitted. principal: string uri or nsiprincipal for the sandbox. if omitted defaults to system principal. ...
...ri or nsiprincipal for the sandbox. if omitted defaults to system principal. prototype: object that the returned sandbox will inherit from. defaults to {}. wantxrays: a boolean value indicating whether code outside the sandbox wants x-ray vision with respect to objects inside the sandbox. defaults to true. let sandbox = sandbox({ name: 'resource:///modules/foo/bar.js', wantxrays: false, prototype: { console: { log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '), error: dump.bind(dump, 'error: ') } } }); evaluate() evaluates code in the supplied sandbox. if options.source is provided then its value is evaluated, otherwise source is read from the supplied uri. either way, any exceptions will be reported as from ...
dev/panel - Archive of obsolete content
}); in the constructor definition there are a number of mandatory and optional parameters for you to supply. name type description label string the string to display in the toolbox toolbar. mandatory icon string the icon to display in the toolbox toolbar, speci...
...}); in the constructor definition there are a number of mandatory and optional parameters for you to supply. name type description label string the string to display in the toolbox toolbar. mandatory icon string the icon to display in the toolbox toolbar, specified as a resource:// url...
Forms related code snippets - Archive of obsolete content
tnode) { otable.parentnode.removechild(otable); return; } otable.style.zindex = nzindex++; otable.style.position = "absolute"; otable.style.left = otarget.offsetleft + "px"; otable.style.top = (otarget.offsettop + otarget.offsetheight) + "px"; otarget.parentnode.insertbefore(otable, otarget); }; ainstances.push(this); } datepicker.prototype.writedays = function () { const nendblanks = (this.current.getday() + bzeroismonday * 6) % 7, nend = amonthlengths[this.current.getmonth()] + nendblanks, ntotal = nend + ((7 - nend % 7) % 7); var otd, otr; if (this.otbody) { this.container.removechild(this.otbody); } this.otbody = document.createelement("tbody"); for (var nday, oday, niter = 0; n...
... through a <fieldset> of radioboxes and textboxes (written in pure css, without javascript), please see this example. autogrowing <textarea> this example shows how to make a textarea really autogrowing during a typing. insert some custom text in a <textarea> this example shows how to insert some html tags or smiles or any custom text in a textarea. image preview before upload the filereader.prototype.readasdataurl() method can be useful, for example, to get a preview of an image before uploading it.[article] this example shows how to use it in this way. note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code you can see our crossbrowser possible solution for image preview. filter the digitation into a form field this e...
LookupNamespaceURI - Archive of obsolete content
aces (e.g., those set with node.prefix). ...
...lobals document, htmldocument */ (function () { 'use strict'; var doc = typeof document !== 'undefined' ? document : htmldocument; // support htmldocument if document not present // if document is present, is this method also present? ...
Miscellaneous - Archive of obsolete content
lid.url")) another similar alternative (using both getstringfromname and formatstringfromname), is: var fcbundle = components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"); function getstr(msg, args){ //get localised message if (args){ args = array.prototype.slice.call(arguments, 1); return fcbundle.formatstringfromname(msg,args,args.length); } else { return fcbundle.getstringfromname(msg); } } /* usage */ alert(getstr("invalid.url", "http://bad/url/", "3")); //for message with parameters alert(getstr("invalid.url")); //for message without parameters getting postdata of a webpage first, you need to get the browser you want, and its hi...
...code in the components/certsservice.js file: const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); const gobserver = cc['@mozilla.org/observer-service;1'].getservice(ci.nsiobserverservice); const gioservice = cc["@mozilla.org/network/io-service;1"].getservice(ci.nsiioservice); function certsservice() {} certsservice.prototype = { observe: function(asubject, atopic, adata) { switch(atopic) { case "app-startup": gobserver.addobserver(this,"xpcom-shutdown",false); gobserver.addobserver(this,"final-ui-startup",false); break; case "xpcom-shutdown": gobserver.removeobserver(this,"final-ui-startup"); gobserver.
Extension Etiquette - Archive of obsolete content
g different themes. extension icons unique icons are usually worth their download weight. they allow for easy identification among other extensions in the extensions manager. coding practices namespace conflicts there are many namespaces which extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. these often include areas such as: object prototypes, such as string.prototype, which are often extended to add methods to native objects. global variables, such as top-level declarations on scripts loaded into shared windows or web pages. expando properties of shared objects, such as document objects, or dom nodes. ids and class names in html and xul documents, when extensions add elements to web pages or browser windows. chrome: or resource:...
...in general, care must be taken whenever defining a name anywhere that other code might do likewise. strategies to avoid such conflicts include: avoid shared namespaces where possible many naming conflicts are best avoided by simply not sharing namespaces. scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts. expando properties are best avoided using tools such as weakmaps. prefix names in shared namespaces when shared namespaces can't be avoided, the simplest solution to prevent conflicts is to use a distinct prefix for all of your names. class names for html elements created by the cool beans extension, for instance, might all be prefixed with cool-beans-. global variables might all b...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
on’t use any filenames that have whitespace in them. usage an rpn calculator we’re going to implement a simple rpn3 calculator in javascript to see how this can be used. on the program side, we’ll create a class called rpncalc. first we’ll sketch out a simple interface for it (listing 1). save this as a file called calc.js. listing 1: calc.js (stage 1) function rpncalc() { } rpncalc.prototype = { init: function() { }, push: function(val) { }, plus: function() { }, pop: function() { } } implement the addition operation create test case begin by creating the test case. first, select the menu item tools:mozlab:open mozunit runner to bring up the mozunit window. select the menu item file:new, and save test_calc.js in the same directory as the file that is the test targ...
...tcase('rpn calc testcase'); var module = new modulemanager(); var rpncalc = module.require('package', 'calc'); tc.tests = { '2 1 +': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.plus(); assert.equals(calc.pop(), 3); } } listing 3: additional content for calc.js function rpncalc() { this.stack = new array(); } rpncalc.prototype = { init: function() { this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(func(a, b)); }, plus: function() { return this._letfunc(this._plus); }, _plus: function(a, b) { return a + b; }, pop: function() { return this.stack.pop(); } } check...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
eb services like google maps, which used javascript and asynchronous communications, created an awareness of a set of technologies nicknamed ajax (asynchronous javascript and xml); that plus the advent of a number of libraries that paper over implementation differences between different web browsers has more recently led to a re-evaluation of javascript as a programming language. javascript is a prototype-based object-oriented language, and as shown in listing 3, also permits independent class definitions. it does not have strict typing like java, making it extremely flexible and giving it qualities that in some senses could be considered similar to lisp. firefox 3.5 includes a number of extensions to the specification standardized in ecmascript 3rd edition, and can use javascript 1.7 and javascr...
...ns. it does not have strict typing like java, making it extremely flexible and giving it qualities that in some senses could be considered similar to lisp. firefox 3.5 includes a number of extensions to the specification standardized in ecmascript 3rd edition, and can use javascript 1.7 and javascript 1.8. listing 3: an example of a class definition in javascript function myclass() { } myclass.prototype = { property1 : true, property2 : 'string', method : function() { alert('hello, world!'); } }; var obj = new myclass(); obj.method(); dom: an api for manipulating xml documents the document object model (dom) is a technical standard promulgated by the w3c, and is an api for manipulating the contents of xml documents as objects. in earlier dynamic html approaches, the typical method...
JavaScript Object Management - Archive of obsolete content
or a remote api. data will often be translated into arrays of entities, and those are better represented through classes. one way to define a class is as follows: /** * user class. represents a hello world user (whatever that may be). */ 〈modulenamespace〉.user = function(aname, aurl) { this._name = aname; this._url = aurl; }; /** * user class methods. */ 〈modulenamespace〉.user.prototype = { /* the name of the user. */ _name : null, /* the url of the user. */ _url : null, /** * gets the user name. * @return the user name. */ get name() { return this._name; }, /** * gets the user url. * @return the user url. */ get url() { return this._url; } }; in this example we defined a fictitious user class for the hello world extension. u...
...ser url. * @return the user url. */ get url() { return this._url; } }; in this example we defined a fictitious user class for the hello world extension. using the function keyword to define a class is odd, but this is just the javascript way: functions are also objects. the definition of the class acts as a constructor as well, and then you can define all other members using the prototype attribute. in this case we defined "getter" properties for the name and url members. this way we have immutable instances of our class. well, only if consumers of the class play nice and don't change anything they shouldn't. creating an instance and using it is simple enough: let user = new 〈modulenamespace〉.user("pete", "http://example.com/pete"); window.alert(user.name); this is so...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
// 4) call ldap servers to get ldap attribut...
... new array('ldap2.int-evry.fr', 'ldap1.int-evry.fr', 'openldap.int-evry.fr' ); // shuffle function to randomize the server array /** * setup the shuffle method for an array, from "mickweb script * factory" at: * http://www.mickweb.com/javascript/arrays/pureshuffle.html */ // setup the shuffle method for an array array.prototype.shuffle = function(times) { var i,j,t,l=this.length; while(times--) { with(math) { i = floor(random()*l); j = floor(random()*l); } t = this[i]; this[i] = this[j]; this[j] = t; } return this; } // mix up the ldap servers so we don't hit the same one each time ldap_servers.shuffle(10); /* 3) define here (because if set after "4)" bel...
Monitoring WiFi access points - Archive of obsolete content
ifi access points to obtain information about them including their ssid, mac address, and signal strength. this capability was introduced primarily to allow wifi-based location services to be used by geolocation services. example this example simply displays a list of the available access points. ...
...this object is described in lines 11 through 40 in the code above. the onchange() method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points. then the loop in lines 19-22 iterates over the list of access...
Dehydra Object Reference - Archive of obsolete content
accessing member variables or nonstatic member functions of aggregate types, e.g. the "foo" variable would be a .fieldof membervar/fn in foo->membervar or foo->memberfn(). note that when constructing the return value of a function (e.g. return t();), no container variable is available; in this case, .isreturn will be true (see function variable). variables can identified by their dehydradecl() prototype. function variable function objects are an extension of variable objects. the following additional properties are available on functions: property type description .isvirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g. virtual void foo() = 0;). .isconstructor boolean flag constructors generally have a .fieldof attribute (see variable objects). .isfuncti...
...operty type description .isvirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g. virtual void foo() = 0;). .isconstructor boolean flag constructors generally have a .fieldof attribute (see variable objects). .isfunction boolean flag true for function variables. type objects dehydra provides detailed type objects. dehydra type objects use the dehydratype() prototype. common type properties property type description .name string if applicable, the name of of the type. for typedefs and classes, this is the declared name. for built-in types this is the standard name such as "int". some types such as bitfields may not have names. .typedef type object if this is a typedef, the original type. .isconst boolean flag .isvolatile boolean flag ...
Venkman Introduction - Archive of obsolete content
the stop button dismisses the stop mode and specifies that scripts should be executed normally, without pausing as each statement is executed. the pretty print button toggles pretty print mode. while in pretty print mode, the contents of the source view will contain the decompiled source text for the selected function. this is the same text you would get from the tosource method of the function prototype. if the source text you are debugging is poorly formatted, pretty print can help make it easier to read by inserting line breaks and whitespace in appropriate places. when pretty print is enabled you will see a green check mark on the toolbar button, and the menu item will be checked as well. the loaded scripts view the loaded scripts view is in the top left portion of the window. when a fil...
... the "find creator" command. by default, properties of type function are not displayed, in order to conserve space in the view. if you would like to have functions displayed, check the "include functions" menu item in the view's context menu. you may need to close and re-open any objects you had open to see the change. properties that show up in a bold grey font are defined on an object from the prototype chain, and not on the actual object you are inspecting. if you would like to inspect the object's prototype and parent chains, check the "include ecma properties" menu item in the view's context menu. if a property shows up in a bold red font, an exception occurred when venkman tried to read the value. the exception object will appear as the value of the property. icon data type ...
XULRunner Hall of Fame - Archive of obsolete content
d your photos to flickr. source google adwords editor adwords editor is google's free, downloadable account management application for your computer. latest release 7.6.1 january 2010 - xulrunner patches lotus notes / sametime the latest version of ibm lotus notes and sametime can embed xul application. mockery mockery is a gui design tool for creating and editing mockups, prototypes, and wireframes for web and desktop software. latest release august 2010 plain old webserver google warns that this link is unsafe. a fully-functioning webserver that runs server-side javascript. latest release june 2009 prism (formerly known as webrunner) a simple, minimal web browser shell or "single site browser." useful for running web applications such as gmail in a separate...
...imple, minimal web browser shell or "single site browser." useful for running web applications such as gmail in a separate browser process. songbird songbird™ is a desktop web player, a digital jukebox and web browser mashup. build instructions spicebird a collaboration suite - e-mail, calendaring and instant messaging. latest release: june 2010 - build instructions utilities / prototypes ajax toolkit framework (atf) a part of the eclipse web tools platform (wtp) aliwal geocoder geocode addresses onto a map benjamin's xulrunner examples "mybrowser is a very simple example browser", xulmine. an updated version of "mybrowser" that works with firefox 25.0.1+ is available in matthew kastor's xulrunner examples at https://github.com/matthewkastor/xulrunner-exa...
2006-11-24 - Archive of obsolete content
proposal for an event summary dialog discussions about design for an event summary dialog. ...
... proposal for an event summary dialog discussions about design for an event summary dialog. ...
Iterator - Archive of obsolete content
re, and will be removed at some point. for future-facing usages, consider using for..of loops and the iterator protocol. the iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. syntax iterator(object, [keyonly]) parameters object object to iterate over properties. keyonly if keyonly is truthy value, iterator.prototype.next returns property_name only. description returns iterator instance that iterates over object. iterator instance returns [property_name, property_value] array for each iteration if keyonly is falsy, otherwise, if keyonly is truthy, it returns property_name for each iteration. if object is the iterator instance or generator instance, it returns object itself. properties iterator.protot...
... over object. iterator instance returns [property_name, property_value] array for each iteration if keyonly is falsy, otherwise, if keyonly is truthy, it returns property_name for each iteration. if object is the iterator instance or generator instance, it returns object itself. properties iterator.prototype[@@iterator] returns a function that returns iterator object. methods iterator.prototype.next returns next item in the [property_name, property_value] format or property_name only. it throws stopiteration if there are no more items. examples iterating over properties of an object var a = { x: 10, y: 20, }; var iter = iterator(a); console.log(iter.next()); // ["x", 10] console.log(iter.next()); // ["y", 20] console.log(iter.next()); // throws stopiteration iterating over pr...
New in JavaScript 1.8.5 - Archive of obsolete content
the following is a changelog for javascript 1.8.5. this version was included in firefox 4. new features in javascript 1.8.5 new functions function description object.create() creates a new object with the specified prototype object and properties. bug 492840 object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. object.getownpropertydescriptor() returns a property descriptor for a named ...
...2845 object.freeze() freezes an object: other code can't delete or change any properties. bug 492844 object.isfrozen() determines if an object was frozen. bug 492844 array.isarray() checks if a variable is an array. bug 510537 date.prototype.tojson() returns a json format string for a date object. function.prototype.bind() creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507 new ecmascript5 features get and set operators ...
Object.observe() - Archive of obsolete content
hanged object after the change was made. type: a string indicating the type of change taking place. one of "add", "update", or "delete". oldvalue: only for "update" and "delete" types. the value before the change. acceptlist the list of types of changes to be observed on the given object for the given callback. if omitted, the array ["add", "update", "delete", "reconfigure", "setprototype", "preventextensions"] will be used. return value the object to be observed. description callback is called each time a change is made to obj, with an array of all changes in the order in which they occurred. examples logging all six different types var obj = { foo: 0, bar: 1 }; object.observe(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object...
...e(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}] obj.foo = 'hello'; // [{name: 'foo', object: <obj>, type: 'update', oldvalue: 0}] delete obj.baz; // [{name: 'baz', object: <obj>, type: 'delete', oldvalue: 2}] object.defineproperty(obj, 'foo', {writable: false}); // [{name: 'foo', object: <obj>, type: 'reconfigure'}] object.setprototypeof(obj, {}); // [{name: '__proto__', object: <obj>, type: 'setprototype', oldvalue: <prototype>}] object.seal(obj); // [ // {name: 'foo', object: <obj>, type: 'reconfigure'}, // {name: 'bar', object: <obj>, type: 'reconfigure'}, // {object: <obj>, type: 'preventextensions'} // ] data binding // a user model var user = { id: 0, name: 'brendan eich', title: 'mr.' }; // create a gree...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
a function signature (or type signature, or method signature) defines input and output of functions or methods. a signature can include: parameters and their types a return value and type exceptions that might be thrown or passed back information about the availability of the method in an object-oriented program (such as the keywords public, static, or prototype). in depth signatures in javascript javascript is a loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. the type will get determined automatically while the program is being processed. a signature in javascript can still give you some information about the method: myobject.prototype.myfunction(value) the method is installed on an object called myobject. the ...
...loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. the type will get determined automatically while the program is being processed. a signature in javascript can still give you some information about the method: myobject.prototype.myfunction(value) the method is installed on an object called myobject. the method is installed on the prototype of myobject (thus it is an instance method) as opposed to being a static method. the name of the method is myfunction. the method accepts one parameter, which is called value and is not further defined. signatures in java in java, signatures are used to identify methods and classes at the level of the virtual machine code. you have to declare types of variables in your code in order to be ab...
Test your skills: Object-oriented JavaScript - Learn web development
note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). oojs 1 in this task we provide you with a constructor. we want you to: add a new method to the shape class's prototype, calcperimeter(), which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console. create a new instance of the shape class called square. give it a name of square and a sidelength of 5. call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as expected. create a new instance of s...
Creating Sandboxed HTTP Connections
// create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); // get a channel for that nsiuri gchannel = ioservice.newchannelfromuri(uri); // get an listener var listener = new streamlistener(callbackfunc); gchannel.notificationcallbacks = listener; gchannel.asyncopen(listener, null); function streamlistener(acallbackfunc) { this.mcallbackfunc = acallbackfunc; } streamlistener.prototype = { mdata: "", // nsistreamlistener onstartrequest: function (arequest, acontext) { this.mdata = ""; }, ondataavailable: function (arequest, acontext, astream, asourceoffset, alength) { var scriptableinputstream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscriptableinputstream); scriptableinputstream.i...
....ns_nointerface; } }; quick note: storing the channel in a global (especially in an extension) isn't a good idea, but was done to make the code easier to read. it would be better to have the entire implementation inside a class and storing the channel as a member: function myclass() { this.mchannel = null; // ... var listener = new this.streamlistener(callbackfunc); // ... } myclass.prototype.streamlistener = function (acallbackfunc) { return ({ mdata: "", // ... }) } handling cookies when sending a request, cookies that apply to the url are sent with the http request. the http response can also contain cookies, which the browser processes. as of mozilla 1.8.1 (firefox 2), it is now possible to intercept those two cases. for example, this means that if the user was logg...
PromiseWorker.jsm
rted (note that stopiteration is deprecated). you can also construct and throw your own custom error objects as needed. when custom error is caught by abstractworker, tomsg method will be called to convert it into message. the tomsg function should return an object which has exn property, that is the property key for the frommsg function in main thread side. // worker // define a custom error prototype. function customerror(message) { this.message = message; } customerror.prototype.tomsg = function() { return { exn: 'customerror', message: this.message, }; }; // a function called by message. function func() { ... // throw a custom error. throw new customerror('meow'); } the converted message will be posted back to the main thread, and it will be converted again to error o...
...nc() { ... // throw a custom error. throw new customerror('meow'); } the converted message will be posted back to the main thread, and it will be converted again to error object, with frommsg function specified for the error in exceptionhandlers property. this is seen in a simple demo github :: promiseworker custom errors demo - main thread setup. // main thread // define a custom error prototype. function customerror(message) { this.message = message; } customerror.frommsg = function(msg) { return new customerror(msg.message); }; // register a constructor. myworker.exceptionhandlers['customerror'] = customerror.frommsg; this is seen in a simple demo at github :: promiseworker custom errors demo - worker side setup. the complete demo is found here: github :: promiseworker custom e...
XPCOMUtils.jsm
. define the nsgetfactory() or nsgetmodule() entry point. pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above. constructor the constructor is a simple method that handles any required initialization tasks. function mycomponent() { // initialize the component here } class declaration declare the class prototype, using a form similar to this. mycomponent.prototype = { // properties required for xpcom registration: classdescription: "unique text description", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", // [optional] custom factory (an object implementing nsifactory). if not // provided, the default factory is used, which ...
...rateqi( interfaces ); parameters interfaces an array of interfaces implemented by the component. return value a queryinterface() function implementation. remarks when you implement an interface that inherits from another one, you should generally list all the base interfaces explicitly, except for nsisupports. for example, if your component implements nsistreamconverter: mycomponent.prototype = { queryinterface: xpcomutils.generateqi([ components.interfaces.nsirequestobserver, components.interfaces.nsistreamlistener, components.interfaces.nsistreamconverter, ]), // ...methods... } importrelative() imports a javascript code module given the calling javascript code module's global object (you should specify this) and a path relative to that module. this lets module...
NSS_3.12_release_notes.html
s bug 356595: on windows, rng_systeminfoforrng calls getcurrentprocess, which returns the constant (handle)-1. bug 357015: on windows, readsystemfiles reads 21 files as opposed to 10 files in c:\windows\system32. bug 361076: clean up the use_pthreads related code in coreconf/sunos5.mk. bug 361077: clean up the use_pthreads related code in coreconf/hp-ux*.mk. bug 402114: fix the incorrect function prototypes of ssl handshake callbacks bug 402308: fix miscellaneous compiler warnings in nss/cmd bug 402777: lib/util can't be built stand-alone. bug 407866: contributed improvement to security/nss/lib/freebl/mpi/mp_comba.c bug 410587: ssl_getchannelinfo returns secsuccess on invalid arguments bug 416508: fix a _msc_ver typo in sha512.c, and use sec_begin_protos/sec_end_protos in secport.h bug 419242: 'all...
... use of obsolete typedefs in public nss headers bug 113323: the first argument to pk11_findcertfromnickname should be const. ...
Rhino overview
ater are ecma 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 w...
...rns 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 elements but with length property equal to i). string.prototype.substring for version 1.2 only, the two arguments are not swapped if the first argument is less than the second one. all other versions are ecma compliant. string.prototype.split for version 1.2 only, split performs the perl4 special case when given a single space character as an argument (skips leading whitespace, and splits on whitespace). all other versions split on the space character prop...
Invariants
trees have it cleared. if an object is inextensible, its dslots will never again change. (we don't bother locking when accessing slots of a sealed object. the locking is going away regardless.) compartments suppose obj = js_getscopechain(cx) is not null. then cx->compartment == obj->compartment(). when a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often determined by examining the scope chain. the object and its proto and parent must be in the same compartment. so it is utterly crucially important that this invariant always be true if objects are being created. the public api for compartment-hopping, jsautoentercompartment, and the internal api, js::autocompartment, both make sure the invariant is maintained. however, there is another...
...partment-hopping, jsautoentercompartment, and the internal api, js::autocompartment, both make sure the invariant is maintained. however, there is another internal api, js::switchtocompartment, that lets you break this invariant, and of course in xpconnect we use that from time to time when we know we aren't going to be creating any new objects (other than global objects, which have no parent or prototype) or doing anything that might call back into native code that could create objects. we do this in order to save some cpu cycles (in other words, for no good reason whatsoever). if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment. while executing a script, cx->compartment == script->compartment. but this is true only so long as we are actuall...
JIT Optimization Strategies
ptimizes access to properties which are implemented by a getter function, where the getter is shared between multiple types. this optimization applies most often when the property access site is polymorphic, but all the object types are derived variants of a single base class, where the property access refers to a getter on the base class. consider the following example: function base() {} base.prototype = { get x() { return 3; } }; function derived1() {} derived1.prototype = object.create(base.prototype); function derived2() {} derived1.prototype = object.create(base.prototype); if a property access for d.x sees only instances of both derived1 and derived2 for d, it can optimize the access to x to a call to the getter function defined on base. this optimization applies to shared getters on ...
...ptimizes access to properties which are implemented by a setter function, where the setter is shared between multiple types. this optimization applies most often when the property access site is polymorphic, but all the object types are derived variants of a single base class, where the property access refers to a setter on the base class. consider the following example: function base() {} base.prototype = { set x(val) { ... } }; function derived1() {} derived1.prototype = object.create(base.prototype); function derived2() {} derived1.prototype = object.create(base.prototype); if a property write for d.x = val sees only instances of both derived1 and derived2 for d, it can optimize the write to x to a call to the setter function defined on base. this optimization applies to shared setters on...
JSClass
, js_propertystub, js_propertystub, js_enumeratestub, js_resolvestub, js_convertstub, null, jsclass_no_optional_members }; to expose this class to scripts, and to attach methods and properties to it, use js_initclass. private data custom classes very often need to store private c/c++ data that should not be visible to scripts. to do this, use the jsclass_has_private (jsclass_construct_prototype wad removed) flags. implement a jsnative constructor function that allocates this private data and stores it in the new object using js_setprivate. implement a jsclass.finalize callback that frees the private data. each native getter, setter, or method can access the private data using js_getinstanceprivate. when initializing the class, pass the jsnative constructor function to js_initclass. (t...
... * js_set_rval(cx, vp, object_to_jsval(obj)); */ return true; } { js_initclass(cx, global, js::null(), &printer_class, printer_construct, 1, null, null, null, null); } see also mxr id search for jsclass jsclass.flags js_getclass js_initclass js_newobject js_newobjectforconstructor js_instanceof bug 638291 - added trace bug 702507 - removed jsclass_construct_prototype bug 726944 - removed xdrobject, reserved0 and reserved1 bug 886829 - made finalize optional bug 957688 - removed checkaccess bug 1103368 - made most of members optional bug 1097267 - removed jsclass_new_enumerate bug 1054756 - removed convert bug 1261723 - class ops are moved to a sub-structure jsclassops ...
JSExtendedClass.wrappedObject
proto__ or __parent__ from script, the javascript engine checks to see if the assignment would produce a cycle. if so, it fails with an exception. when walking the chain to do this check, wrappers are automatically unwrapped. a wrapper object is strictly equal to the object it wraps, in the sense of === and !==. two wrapper objects that wrap the same object are also strictly equal. object.prototype.eval unwraps. a wrapper object that wraps an array is considered an array for the purpose of array.prototype.concat and array.concat (which treat array arguments differently from other arguments, per ecma 262-3 §15.4.4.4). the wrappedobject callback implementation must never fail. if it returns null or obj, then the js engine treats the object as though it were not a wrapper. wrapper obje...
...rapper object that wraps an array is considered an array for the purpose of array.prototype.concat and array.concat (which treat array arguments differently from other arguments, per ecma 262-3 §15.4.4.4). the wrappedobject callback implementation must never fail. if it returns null or obj, then the js engine treats the object as though it were not a wrapper. wrapper objects typically have no prototype, do not allow setting __proto__, and inherit properties from the wrapped object rather than the prototype chain (see jsnewresolveop). ...
JSNewResolveOp
lehandleobject out parameter. on success, the resolve hook must set *objp to the object in which the property has been defined, or null if it was not defined. description like jsresolveop, but flags provide contextual information about the property access. on success, the callback must set the *objp out parameter to null if id was not resolved; or non-null, referring to obj or one of its prototypes, if id was resolved; and return js_true. on failure, it must return js_false. this hook instead of jsresolveop is called via the jsclass.resolve member if jsclass_new_resolve is set in jsclass.flags. setting jsclass_new_resolve and jsclass_new_resolve_gets_start further extends this hook by passing in the starting object on the prototype chain via *objp. thus a resolve hook implementation may de...
...when using jsclass_new_resolve_gets_start, the resolve hook must therefore null *objp to signify "not resolved". ...
JSObjectOps.getProperty
not api documentation. see bug 408416 for details. jsobjectops.getproperty, setproperty, and deleteproperty are high-level callbacks that implement object property accesses. each of these callbacks is responsible for everything involved with an individual property access operation, including: any locking necessary for thread safety; security checks; finding the property, including walking the prototype chain if needed; calling the lower-level jsclass hooks; calling getters or setters; and actually getting, setting, or deleting the property once it is found. contrast jsclass.getproperty, jsclass.setproperty, and jsclass.delproperty, which are hooks called during property accesses and don't have to implement any of that. syntax typedef jsbool (*jspropertyidop)( jscontext *cx, jsobject *ob...
... description get, set, or delete obj[id], returning js_false on error or exception, js_true on success. if getting or setting, the new value is returned in *vp on success. if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype chain). this reflects the quirky behavior of delete as specified in ecma 262-3 §11.4.1 and ecma 262-3 §8.6.2.5. ...
JSObjectOps.setProto
owsers, its use is discouraged since it could be removed at any time. try to avoid using it. warning! jsobjectops is not a supported api. details of the api may change from one release to the next. this documentation should be considered spidermonkey internals documentation, not api documentation. see bug 408416 for details. the jsobjectops.setproto and setparent callbacks implement the js_setprototype and js_setparent functions. these callbacks share the same type, jssetobjectslotop. syntax typedef jsbool (*jssetobjectslotop)(jscontext *cx, jsobject *obj, uint32 slot, jsobject *pobj); name type description cx jscontext * pointer to the js context in which the object's prototype or parent is being modified. obj jsobject * the object whose pr...
...context * pointer to the js context in which the object's prototype or parent is being modified. obj jsobject * the object whose prototype or parent is being modified. slot uint32 the index of the slot being modified: jsslot_proto for the jsobjectops.setproto callback, and jsslot_parent for the jsobjectops.setparent callback. pobj jsobject * the new prototype or parent object. description these hooks must check for cycles without deadlocking, and otherwise take special steps. see js_setprototype or js_setparent in js/src/jsobj.cpp for an example. ...
JSPropertyOp
alue of the left-hand side after assignment, as opposed to the value of the right-hand side, as required by ecma 262-3 §11.13. this ecmascript incompatibility is observable when assigning to the length property of an array, for example. this incompatibility will be fixed in spidermonkey 1.8; see bug 312354. inherited properties. note that in javascript, an object can inherit properties from its prototype. getters (and sometimes setters; see js_setproperty for details) are called even when the property being accessed is found on a prototype and not on obj itself. in this case obj points to the object from which the property is being accessed, not the object on which the property was defined. jsclass hooks jsclass offers following hooks: jspropertyop jsclass.addproperty is called just afte...
... callback is called with obj locked. it is therefore dangerous for the callback to call jsapi functions, particularly if obj may have been visible to more than one thread. jsclass.getproperty is the default getter for new properties. see the section on getters and setters above. jsclass.getproperty is also called when a program attempts to get a property that does not exist on obj or any prototype. on entry, *vp contains the property's stored value, or undefined if the property doesn't exist or doesn't have a stored value. the callback may modify *vp. on success, the post-callback value of *vp is returned to the caller. this value also becomes the property's new stored value, if the property exists and has a stored value. jsstrictpropertyop jsclass.setproperty is the default s...
JS_GetClassObject
get the builtin class constructor. syntax bool js_getclassobject(jscontext *cx, jsprotokey key, js::mutablehandle<jsobject*> objp); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. key jsprotokey the key of the prototype. objp js::mutablehandle&lt;jsobject*&gt; out parameter. if successful, receive the class constructor. description js_getclassobject gets the builtin class costructor for the specified prototype key. if successful, js_getclassobject stores the class constructor to *objp and returns true, otherwise returns false and the value of *objp is undefined. see also mxr id search for js_getclassobject j...
...e&lt;jsobject*&gt; out parameter. if successful, receive the class constructor. description js_getclassobject gets the builtin class costructor for the specified prototype key. ...
JS_GetLocaleCallbacks
if expose_intl_api is defined, intl api is used instead. jslocaletounicode convert locale specific string to unicode string. description js_setlocalecallbacks establ...
...mpare)(jscontext *cx, js::handlestring src1, js::handlestring src2, js::mutablehandlevalue rval); typedef bool (* jslocaletounicode)(jscontext *cx, const char *src, js::mutablehandlevalue rval); type description jslocaletouppercase implementation of string.prototype.tolocaleuppercase() function. jslocaletolowercase implementation of string.prototype.tolocalelowercase() function. jslocalecompare implementation of string.prototype.localecompare() function. if expose_intl_api is defined, intl api is used instead. jslocaletounicode convert locale specific string to unicode string. description js_setlocalecallbacks establishes locale callbacks. the pointer must persist as long as the jsruntime. passing nullptr restor...
JS_HasInstance
ript. syntax bool js_hasinstance(jscontext *cx, js::handle<jsobject*> obj, js::handle<js::value> v, bool *bp); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; constructor/prototype to test. v js::handle&lt;js::value&gt; the value to test. bp bool * out parameter. on success, *bp receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof...
... receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof test in *bp and returns true. on error or exception, it returns false, and the value left in *bp is undefined. when providing a prototype as obj, the prototype's jsclass must have its hasinstance method set. otherwise js_hasinstance returns false. see also mxr id search for js_hasinstance js_instanceof ...
JS_IsConstructing_PossiblyWithGivenThisObject
aybethis); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp const jsval * maybethis jsobject ** description in the case of a constructor called from js_constructobject and js_initclass where the class has the jsclass_construct_prototype flag set, spidermonkey passes the constructor a non-standard this object. in such cases, the following example would provide the additional information of whether a special this was supplied. jsbool foo_native(jscontext *cx, unsigned int argc, jsval *vp) { jsobject *maybethis; if (js_isconstructing_possiblywithgiventhisobject(cx, vp, &maybethis)) { // native called as a constructor i...
... see also bug 702507 ...
JS_LookupProperty
he length of name in characters; or -1 to indicate that name is null-terminated. flags unsigned (only in js_lookuppropertywithflags) a combination of bits requesting special search behavior. see flags below. objp js::mutablehandleobject out parameter. on success, *objp receives the object on which the property was found. this will be either obj or an element on obj's prototype chain. vp js::mutablehandleobject out parameter. on success, *vp receives the stored value of the property, if any. description the functions js_lookupproperty, js_lookupucproperty, js_lookuppropertybyid, js_lookuppropertywithflags, and js_lookuppropertywithflagsbyid search a specified object, obj, for a property with the given name. these functions all have similar behavior:...
... parameter. on success, *vp receives the stored value of the property, if any. description the functions js_lookupproperty, js_lookupucproperty, js_lookuppropertybyid, js_lookuppropertywithflags, and js_lookuppropertywithflagsbyid search a specified object, obj, for a property with the given name. these functions all have similar behavior: the search starts with obj and proceeds along the prototype chain. if the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the return value is true. if neither obj nor any of its prototypes have such a property, *vp receives undefined and the return value is true (to indicate no error occurred). on error or exception (such as running out of memory during the search), the return value is false...
JS_ValueToId
a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the js value to convert. s js::handlestring the js string to convert. index uint32_t an unsigned integer index of array to convert. chars js::twobytechars the string to convert. key jsprotokey the prototype key to convert. idp js::mutablehandleid out parameter. on success, *idp receives the converted jsid. description 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 valu...
...t 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_valuetostring. js_stringtoid and js_charstoid convert a specified string to a jsid. js_indextoid converts a specified integer index to an integer jsid. js::protokeytoid converts a specified prototype key to a jsid. on success, js_valuetoid stores the converted value in *idp and returns true. otherwise it returns false. the inverse of js_valuetoid is js_idtovalue. mxr id search for js_valuetoid see also mxr id search for js_idtovalue mxr id search for js_stringtoid mxr id search for js_indextoid mxr id search for js_charstoid mxr id search for js::protokeytoid js_valuetoid bug 698...
SpiderMonkey 1.8
ore the number 7 in x. now this statement stores the string "7" in x. the new behavior conforms to the ecmascript standard, ecma 262-3 §11.13.1. in certain cases, the javascript engine no longer calls jsclass.resolve callbacks repeatedly, as it did in previous versions. specifically, if a property lookup first calls a resolve hook which does not define the property, then finds the property on a prototype, that result can be cached. future lookups for the same property on the same sort of object may bypass the resolve hook. js_newdouble is now deprecated. use js_newdoublevalue. the security apis js_setcheckobjectaccesscallback, js_setprincipalstranscoder, and js_setobjectprincipalsfinder are still present but are deprecated in this release. in spidermonkey 1.8.1 they will be removed and replaced...
...ack signature jsfastnative instead of jsnative. jsfastnative can be significantly faster, but applications that use spidermonkey's fine-grained security features should heed the warning in its api documentation. new macros js_fs, js_fn, and js_fs_end are recommended for populating jsfunctionspec arrays. js_newobjectwithgivenproto is exactly like js_newobject except that it doesn't use a default prototype object if you pass null. instead the object is created with no prototype. js_alreadyhasownproperty and friends are new functions for examining an object without triggering resolve hooks. it was possible to configure spidermonkey 1.7 to treat c/c++ char strings as utf-8 by compiling with a non-default compiler option. in spidermonkey 1.8, it is no longer necessary to make a special build to get ...
SpiderMonkey 24
older versions of visual studio. in the long run we anticipate removing the environment variable-based overriding when we drop support for versions of visual studio prior to 2010. in the meantime moz_custom_stdint_h is intended to function as a bridge to always using the standard header. for more information on the fixed-size integer types changes, see this blog post. new c apis js_getarrayprototype provides access to the original value of array.prototype. new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). ...list new c++ helpers here... obsolete apis...
...here... deleted apis js_get_class (use js_getclass instead) js_enumerateresolvedstandardclasses js_getglobalobject js_setcstringsareutf8 ...list other deleted apis... api changes break out and discuss all api changes here... jsoption_strict has been renamed to jsoption_extra_warnings. js_setversion has been removed, js version is now set on the compartment instead of context. js_getprototype, takes context as first argument js_encodestringtobuffer takes add context as first argument, js_newruntime adds a js_[use|no]_helper_threads flag delete property in jsclass definitions now use js_deletepropertystub garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one exception to this is js_ma...
SpiderMonkey 45
s javascript 45 includes significant updates to its language features, yo. new c++ apis jsapi is a c++ exclusive api. please note that spidermonkey reserves the js:: namespace for itself for public exports and the js:: namespace for internal use. ...
...e (bug 1159507) js_mayresolvestandardclass (bug 1155946) js_getiteratorprototype (bug 1225392) js_globallexicalscope (bug 1202902) js_hasextensiblelexicalscope (bug 1202902) js_extensiblelexicalscope (bug 1202902) js_initreflectparse (bug 987514) js::toprimitive (bug 1206168) js::getfirstargumentastypehint (bug 1054756) js::objecttocompletepropertydescriptor (bug 1144366) js_setimmutableprototype (bug 1211607) js_getownucpropertydescriptor (bug 1211607) js_hasownpropertybyid (bug 1211607) js_hasownproperty (bug 1211607) js_deleteucproperty (bug 1211607) js::newfunctionfromspec (bug 1054756) js::compilefornonsyntacticscope (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159...
SavedFrame
artment has (a -> c), or it can view all stack frames, including the frames from chrome compartments (a -> b -> c). to view everything, use an xraywrapper. this is the default wrapper. to see the stack as the content compartment sees it, waive the xray wrapper with components.utils.waivexrays: const contentviewofstack = components.utils.waivexrays(somestack); accessor properties of the savedframe.prototype object source the source url for this stack frame, as a string. line the line number for this stack frame. column the column number for this stack frame. functiondisplayname either spidermonkey’s inferred name for this stack frame’s function, or null. asynccause if this stack frame is the asyncparent of other stack frames, then this is a string representing the type of asynchro...
...ple where the promise 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 frame’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 ...
How to build an XPCOM component in JavaScript
if not // provided, the default factory is used, which returns // |(new my...
...// firefox 4.0 and higher else var nsgetmodule = xpcomutils.generatensgetmodule(components); // firefox 3.x so the total simplified version of your component now looks like (of course documentation and comments aren't a bad thing, but as a template something smaller is nice to have): components.utils.import("resource://gre/modules/xpcomutils.jsm"); function helloworld() { } helloworld.prototype = { classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", queryinterface: xpcomutils.generateqi([components.interfaces.nsihelloworld]), hello: function() { return "hello world!"; } }; var components = [helloworld]; if ("generatensgetfactory" in xpcomu...
wrappedJSObject
. example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating one. for simplicity we omit the component registration code. suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function helloworld() { }; helloworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns_error_no_interface; return this; } }; xpconnect wrapping now let's get a reference to our component. in this example we use getservice, but as...
... other interface our component supports. assuming the nsihelloworld interface defines the hello method, we can now call it: > comp.hello() hello world! while this behavior is nice for production code as it forces you to clearly define the interfaces that should be used to access the component, it's inconvenient to write the interfaces (and recompile each time you change them) when working on a prototype of the component. meet wrappedjsobject xpconnect lets you bypass its wrappers and access the underlying js object directly using the wrapper.wrappedjsobject property if the wrapped object allows this. more specifically, as xpconnect source comments say, you can get comp.wrappedjsobject if three conditions are met: comp really is an xpconnect wrapper around a js object. wrappers around non-j...
Activity Manager examples
= process.contextobj; // optional gactivitymanager.addactivity(event); showing a user-defined activity with cancel capability (javascript) this sample improves the previous one by providing an nsiactivitycancelhandler to allow the user to cancel the process. // step 1: create a nsiactivitycancelhandler implementation function canceljunkprocess() { // user stuff here.. } canceljunkprocess.prototype = { cancel: function(aactivity) { let initiator = aactivity.initiator; if (initiator) { let folder = aactivity.getsubjects({})[0]; .... // assuming that the initiator has some way to cancel // the junk processing for given folder if (initiator.cancelfolderop(folder)) { aactivity.state = components.interfaces.nsiactivityprocess.state_canceled; gactivit...
... "nsiactivityprocess", "init"); const nsactevent = components.constructor("@mozilla.org/activity-event;1", "nsiactivityevent", "init"); // step 1: implement nsiactivitycontextdisplayhelper to show a // customized display text for our context type function sendercontextdisplayhelper() { // user stuff here.. ...
Mozilla
fox itself as well as by extensions, in order to avoid code duplication. javascript libraries from mozilla projects in addition to firefox and other applications, mozilla developers have created a number of useful javascript libraries you can use in your projects. documentation for these libraries can be found here. javascript tips javascript-dom prototypes in mozilla when a dom node is accessed from javascript in mozilla, the native c++ dom node is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node. when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (n...
...en xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (nsiclassinfo), the jsobject is a more or less empty jsobject which is not really that special. all the methods that are supposed to show up on this jsobject are actually not properties of the object itself, but rather properties of the prototype of the jsobject for the wrapper (unless the c++ object's class info has the flag nsixpcscriptable::dont_share_prototype set, but lets assume that's not the case here). js-ctypes js-ctypes allows application and extension code to call back and forth to native code written in c. c++ support is possible through vtable pointers see usin...
Debugger.Environment - Firefox Developer Tools
mpting to access its properties (other than inspectable) or call any its methods throws an instance of error. debugger.environment instances protect their referents from the garbage collector; as long as the debugger.environment instance is live, the referent remains live. garbage collection has no visible effect on debugger.environment instances. accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following accessor properties from its prototype: inspectable true if this environment is a debuggee environment, and can therefore be inspected. false otherwise. all other properties and methods of debugger.environment instances throw if applied to a non-inspectable environment. type the type of this environment object, one of the foll...
...operty’s value is null. optimizedout true if this environment is optimized out. false otherwise. for example, functions whose locals are never aliased may present optimized-out environments. when true, getvariable returns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror. function properties of the debugger.environment prototype object the methods described below may only be called with a this value referring to a debugger.environment instance; they may not be used as methods of other kinds of objects. names() return an array of strings giving the names of the identifiers bound by this environment. the result does not include the names of identifiers bound by enclosing environments. getvariable(name) return the ...
Index - Firefox Developer Tools
serve the debuggee’s memory use in various ways: 22 debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. the referent’s properties do not appear directly as properties of the debugger.object instance; the debugger can access them only through methods like debugger.object.prototype.getownpropertydescriptor and debugger.object.prototype.defineproperty, ensuring that the debugger will not inadvertently invoke the referent’s getters and setters. 23 debugger.script a debugger.script instance may refer to a sequence of bytecode in the debuggee or to a block of webassembly code. for the former, it is the debugger api’s presentation of a jsapi jsscript ob...
...orted by the function call path that allocated them. 27 debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. the referent's properties do not appear directly as properties of the debugger.object instance; the debugger can access them only through methods like debugger.object.prototype.getownpropertydescriptor and debugger.object.prototype.defineproperty, ensuring that the debugger will not inadvertently invoke the referent's getters and setters. 28 deprecated tools deprecated, tools over the course of devtools development, we have added several experimental panels to try out new ideas. not all of these have had wide adoption, and due to the cost of mainten...
AudioContext.createJavaScriptNode() - Web APIs
numoutputchannels the number of output channels in the audio stream. ...
...n(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i = 0; i < data.length; ++i) { data[i] = math.sin(this.x++); } } sinewave.prototype.play = function() { this.node.connect(this.context.destination); } sinewave.prototype.pause = function() { this.node.disconnect(); } see also generating tones with the web audio api exploring the html5 web audio: visualizing sound ...
ChildNode.before() - Web APIs
Web › API › ChildNode › before
h the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? argitem : document.createtextnode(string(argitem))); }); this.parentnode.insertbefore(docfrag, this); } }); }); })([element.prototype, characterdata.prototype, ...
... living standard initial definition. ...
DOMTokenList.forEach() - Web APIs
living standard initial def...
... living standard initial definition. browser compatibilit...
Element.getAttributeNames() - Web APIs
empty array. using getattributenames() along with getattribute(), is a memory-efficient and performant alternative to accessing element.attributes. ...
...attribute(), is a memory-efficient and performant alternative to accessing element.attributes. syntax let attributenames = element.getattributenames(); example // iterate over element's attributes for (let name of element.getattributenames()) { let value = element.getattribute(name); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } return result; }; } specifications specification status comment domthe definition of 'element.getattributenames' in that specification. ...
Element.getElementsByClassName() - Web APIs
length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). another element (if any are left) will then become item(0). ...
...box" (using array notation). another element (if any are left) will then become item(0). filtering the results using array methods we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value. here we'll find all <div> elements that have a class of test: var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement) { return testelement.nodename === 'div'; }); specifications specification status comment domthe definition of 'element.getelementsbyclassname()' in that specification. living standard initial definition ...
Element.insertAdjacentText() - Web APIs
press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. ...
...r buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. polyfill you can polyfill the insertadjacenttext() method in internet explorer 5.5 (maybe earlier) and higher with the following code: if (!element.prototype.insertadjacenttext) element.prototype.insertadjacenttext = function(type, txt){ this.insertadjacenthtml( type, (txt+'') // convert to string .replace(/&/g, '&amp;') // embed ampersand symbols .replace(/</g, '&lt;') // embed less-than symbols ) } specification specification status comment domthe definition of 'insertadjacenttext()' in that specification. living st...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
aneously reducing the risk of user-discernible delays in operations. ensuring ordering on conditional use of promises one situation in which microtasks can be used to ensure that the ordering of execution is always consistent is when promises are used in one clause of an if...else statement (or other conditional statement), but not in the other clause. ...
...ta is cached fetching data data fetched loaded data fetching data loaded data data fetched even worse, sometimes the element's data property will be set and other times it won't be by the time this code finishes running. ...
IDBKeyRange.includes() - Web APIs
a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfill can be used. ...
...keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfill can be used. ...
NodeList - Web APIs
Web › API › NodeList
llections of nodes, usually returned by properties such as node.childnodes and methods such as document.queryselectorall(). although nodelist is not an array, it is possible to iterate over it with foreach(). it can also be converted to a real array using array.from(). however, some older browsers have not implemented nodelist.foreach() nor array.from(). this can be circumvented by using array.prototype.foreach() — see this document's example. live vs. static nodelists although they are both considered nodelists, there are 2 varieties of nodelist: live and static. live nodelists in some cases, the nodelist is live, which means that changes in the dom automatically update the collection. for example, node.childnodes is live: const parent = document.getelementbyid('parent'); let child_nod...
...d to visit the properties in any particular order. for...of loops will loop over nodelist objects correctly: const list = document.queryselectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked = true; } recent browsers also support iterator methods (foreach()) as well as entries(), values(), and keys(). there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.queryselectorall('input[type=checkbox]'); array.prototype.foreach.call(list, function (checkbox) { checkbox.checked = true; }); specifications specification status comment domthe definition of 'nodelist' in that specification. living standard document object model (dom) level 3 core specificationthe defi...
ParentNode.prepend() - Web APIs
ot available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { return; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? argitem : document.createtextnode(string(argitem))); }); this.insertbefore(docfrag, this.firstchild); } }); }); })([element.prototype, document.prototype, docum...
... living standard initial definition. ...
RTCPeerConnection.getStreamById() - Web APIs
ill need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return. ...
...orresponding to the stream to return. example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available. ...
TextDecoder - Web APIs
bytes = new uint8array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир! constructor textdecoder() returns a newly constructed textdecoder that will generate a code point stream with the decoding method specified in parameters. properties the textdecoder interface doesn't inherit any properties. textdecoder.prototype.encodingread only is a domstring containing the name of the decoder, that is a string describing the method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the error mode is fatal. textdecoder.prototype.ignorebomread only is a boolean indicating whether the byte order marker is ignored. methods the textdecoder interface doesn't inherit any...
...a domstring containing the name of the decoder, that is a string describing the method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the error mode is fatal. textdecoder.prototype.ignorebomread only is a boolean indicating whether the byte order marker is ignored. methods the textdecoder interface doesn't inherit any method. textdecoder.prototype.decode() returns a domstring containing the text decoded with the method of the specific textdecoder object. specifications specification status comment encodingthe definition of 'textdecoder' in that specification. living standard initial definition. ...
Synchronous and asynchronous requests - Web APIs
httprequest object asynchronously in order to switch the content of the read file to a specified listener. function xhrsuccess() { this.callback.apply(this, this.arguments); } function xhrerror() { console.error(this.statustext); } function loadfile(url, callback /*, opt_arg1, opt_arg2, ... ...
...dicate that the request should be handled asynchronously. line 16 actually initiates the request. example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish. ...
Using XMLHttpRequest - Web APIs
plex to be explained here in detail. ...
..., and to upload files: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>sending forms with pure ajax &ndash; mdn</title> <script type="text/javascript"> "use strict"; /*\ |*| |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest.prototype.sendasbinary = function(sdata) { var nbytes = sdata.length, ui8data = new uint8array(nbytes); for (var nidx = 0; nidx < nbytes; nidx++) { ui8data[nidx] = sdata.charcodeat(nidx) & 0xff; } /* send as arraybufferview...: */ this.send(ui8data); /* ...or as arraybuffer (legacy)...: this.send(ui8data.buffer); */ }; } /*\ |*| |*...
Introduction - JavaScript
hecking. javascript follows most java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from livescript to javascript. in contrast to java's compile-time system of classes built by declarations, javascript supports a runtime system based on a small number of data types representing numeric, boolean, and string values. javascript has a prototype-based object model instead of the more common class-based object model. the prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. javascript also supports functions without any special declarative requirements. functions can be properties of objects, executing as loosely typed methods. javascript is a very free-form language compared to j...
...namically typed languages such as hypertalk and dbase. these scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation. javascript compared to java javascript java object-oriented. no distinction between types of objects. inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically. class-based. objects are divided into classes and instances with all inheritance through the class hierarchy. classes and instances cannot have properties or methods added dynamically. variable data types are not declared (dynamic typing, loosely typed). variable data types must be declared (static typing...
Iterators and generators - JavaScript
ount; } iterables an object is iterable if it defines its iteration behavior, such as what values are looped over in a for...of construct. some built-in types, such as array or map, have a default iteration behavior, while other types (such as object) do not. in order to be iterable, an object must implement the @@iterator method. this simply means that the object (or one of the objects up its prototype chain) must have a property with a symbol.iterator key. it may be possible to iterate over an iterable more than once, or only once. it is up to the programmer to know which is the case. iterables which can iterate only once (such as generators) customarily return this from their @@iterator method, whereas iterables which can be iterated many times must return a new iterator on each invocation ...
... syntaxes expecting iterables some statements and expressions expect iterables. for example: the for-of loops, yield*. for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] = new set(['a',...
Keyed collections - JavaScript
ys, and detect whether something is stored at a key. map objects, however, have a few more advantages that make them better maps. the keys of an object are strings or symbols, where they can be of any value for a map. you can get the size of a map easily, while you have to manually keep track of size for an object. the iteration of maps is in insertion order of the elements. an object has a prototype, so there are default keys in the map. (this can be bypassed using map = object.create(null).) these three tips can help you to decide whether to use a map or an object: use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type. use maps if there is a need to store primitive values as keys because object treats each key ...
...?" on the weakmap reference page. one use case of weakmap objects is to store private data for an object, or to hide implementation details. the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps". the private data and methods belong inside the object and are stored in the privates weakmap object. everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because privates is not exported from the module. const privates = new weakmap(); function public() { const me = { // private data goes here }; privates.set(this, me); } public.prototype.method = function () { const me = privates.get(this); // do stuff with private data in `me`... }; module.exports = public; sets...
Text formatting - JavaScript
ollowing \u. '\u00a9' // "©" unicode code point escapes new in ecmascript 2015. with unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use unicode code points up to 0x10ffff. with simple unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. see also string.fromcodepoint() or string.prototype.codepointat(). '\u{2f804}' // the same with simple unicode escapes '\ud87e\udc04' string objects the string object is a wrapper around the string primitive data type. const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascr...
...ining the single character u+1f600 "emoji grinning face" will have length 2. accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the unicode standard. (examples should be added to this page after mdn bug 857438 is fixed.) see also string.fromcodepoint() or string.prototype.codepointat(). a string object has a variety of methods: for example those that return a variation on the string itself, such as substring and touppercase. the following table summarizes the methods of string objects. methods of string method description charat, charcodeat, codepointat return the character or character code at the specified position in string. ...
RangeError: repeat count must be non-negative - JavaScript
it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
RangeError: repeat count must be less than infinity - JavaScript
it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
getter - JavaScript
cument.getelementbyid('bookmarked-notification-anchor'); }, for firefox code, see also the xpcomutils.jsm code module, which defines the definelazygetter() function. get vs. defineproperty while using the get keyword and object.defineproperty() have similar results, there is a subtle difference between the two when used on classes. ...
...l be defined on the instance's prototype, while using object.defineproperty() the property will be defined on the instance it is applied to. class example { get hello() { return 'world'; } } const obj = new example(); console.log(obj.hello); // "world" console.log(object.getownpropertydescriptor(obj, 'hello')); // undefined console.log( object.getownpropertydescriptor( object.getprototypeof(obj), 'hello' ) ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } specifications specification ecmascript (ecma-262)the definition of 'method definitions' in that specification. ...
Array.from() - JavaScript
s of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it. polyfill notes: this algorithm is exactly as specified in ecma-262 6th edition (assuming object and typeerror have their original values and that callback.call() evaluates to the original value of function.prototype.call()). in addition, since true iterables cannot be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ecma-262. // production steps of ecma-262, edition 6, 22.1.2.1 if (!array.from) { array.from = (function () { var symboliterator; try { symboliterator = symbol.iterator ? symbol.iterator ...
...on of ecma-262. ...
AsyncFunction - JavaScript
argn names to be used by the function as formal argument names. ...
...function expression. invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. ...
EvalError - JavaScript
the evalerror object indicates an error regarding the global eval() function. this exception is not thrown by javascript anymore, however the evalerror object remains for compatibility. constructor evalerror() creates a new evalerror object. instance properties evalerror.prototype.message error message. although ecma-262 specifies that evalerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. evalerror.prototype.name error name. inherited from error. evalerror.prototype.filename path to file that raised this error. inherited from error. evalerror.prototype.linenumber line number in file that raised this error. inherited from error. evalerror.prototype.columnnumber column number in line that raised this error. inherited from error. ...
...inherited from error. examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
Function - JavaScript
function) instead. function.caller specifies the function that invoked the currently executing function. this property is deprecated, and is only functional for some non-strict functions. function.displayname the display name of the function. function.length specifies the number of arguments expected by the function. function.name the name of the function. instance methods function.prototype.apply(thisarg [, argsarray]) calls a function and sets its this to the provided thisarg. arguments can be passed as an array object. function.prototype.bind(thisarg[, arg1[, 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. ...
...sarg [, argsarray]) calls a function and sets its this to the provided thisarg. arguments can be passed as an array object. function.prototype.bind(thisarg[, arg1[, 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 construc...
GeneratorFunction - JavaScript
argn names to be used by the function as formal argument names. ...
...pe in which the generatorfunction constructor was called. this is different from using eval with code for a generator function expression. invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples creating a generator function from a generatorfunction() constructor var generatorfunction = object.getprototypeof(function*(){}).constructor var g = new generatorfunction('a', 'yield a * 2'); var iterator = g(10); console.log(iterator.next().value); // 20 specifications specification ecmascript (ecma-262)the definition of 'generatorfunction' in that specification. ...
InternalError - JavaScript
the internalerror object indicates an error that occurred internally in the javascript engine. example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion". constructor internalerror() creates a new internalerror object. instance properties internalerror.prototype.message error message. inherited from error. internalerror.prototype.name error name. inherited from error. internalerror.prototype.filename path to file that raised this error. inherited from error. internalerror.prototype.linenumber line number in file that raised this error. inherited from error. internalerror.prototype.columnnumber column number in line that raised this error. inheri...
...inherited from error. examples too much recursion this recursive function runs 10 times, as per the exit condition. ...
Intl.NumberFormat - JavaScript
ect, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.numberformat() creates a new numberformat object. static methods intl.numberformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. ...
... object. static methods intl.numberformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.numberformat.prototype.format() getter function that formats a number according to the locale and formatting options of this numberformat object. intl.numberformat.prototype.formattoparts() returns an array of objects representing the number string in parts that can be used for custom locale-aware formatting. intl.numberformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. examples basic usage in basic use without specifying a locale, a formatted string ...
Intl.RelativeTimeFormat - JavaScript
tive-examples and send us a pull request. constructor intl.relativetimeformat.relativetimeformat() creates a new intl.relativetimeformat object. static methods intl.relativetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. ...
...ds intl.relativetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.relativetimeformat.prototype.format() formats a value and a unit according to the locale and formatting options of the given intl.relativetimeformat object. intl.relativetimeformat.prototype.formattoparts() returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. intl.relativetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples basic format usage the following example shows how to use a...
Object.freeze() - JavaScript
bject.freeze() method freezes an object. a frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. in addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in. 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 object.freeze(obj) parameters obj the object to freeze. return value the object th...
...o; // throws a typeerror delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added obj.sparky = 'arf'; // throws a typeerror } fail(); // attempted changes through object.defineproperty; // both statements below throw a typeerror. object.defineproperty(obj, 'ohai', { value: 17 }); object.defineproperty(obj, 'foo', { value: 'eit' }); // it's also impossible to change the prototype // both statements below will throw a typeerror. object.setprototypeof(obj, { x: 20 }) obj.__proto__ = { x: 20 } freezing arrays let a = [0]; object.freeze(a); // the array cannot be modified now. a[0] = 1; // fails silently // in strict mode such attempt will throw a typeerror function fail() { "use strict" a[0] = 1; } fail(); // attempted to push a.push(2); // throws a typeerror the...
Object.getOwnPropertyNames() - JavaScript
non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasownproperty()). items on the prototype chain are not listed: function parentclass() {} parentclass.prototype.inheritedmethod = function() {}; function childclass() { this.prop = 5; this.method = function() {}; } childclass.prototype = new parentclass; childclass.prototype.prototypemethod = function() {}; console.log( object.geto...
...nction parentclass() {} parentclass.prototype.inheritedmethod = function() {}; function childclass() { this.prop = 5; this.method = function() {}; } childclass.prototype = new parentclass; childclass.prototype.prototypemethod = function() {}; console.log( object.getownpropertynames( new childclass() // ["prop", "method"] ) ); get non-enumerable properties only this uses the array.prototype.filter() function to remove the enumerable keys (obtained with object.keys()) from a list of all keys (obtained with object.getownpropertynames()) thus giving only the non-enumerable keys as output. var target = myobject; var enum_and_nonenum = object.getownpropertynames(target); var enum_only = object.keys(target); var nonenum_only = enum_and_nonenum.filter(function(key) { var indexinenum = e...
Object.keys() - JavaScript
g of the properties is the same as that given by looping over the properties of the object manually. ...
... /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'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, ...
Object.preventExtensions() - JavaScript
marked as non-extensible. note that the properties of a non-extensible object, in general, may still be deleted. attempting to add new properties to a non-extensible object will fail, either silently or by throwing a typeerror (most commonly, but not exclusively, when in strict mode). object.preventextensions() only prevents addition of own properties. properties can still be added to the object prototype. this method makes the [[prototype]] of the target immutable; any [[prototype]] re-assignment will throw a typeerror. this behavior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable. there is no way to make an object extensible again once it has been made non-extensible. examples using object.preventextensions // object.preventext...
...xtensible = { removable: true }; object.preventextensions(nonextensible); object.defineproperty(nonextensible, 'new', { value: 8675309 }); // throws a typeerror // in strict mode, attempting to add new properties // to a non-extensible object throws a typeerror. function fail() { 'use strict'; // throws a typeerror nonextensible.newproperty = 'fail'; } fail(); a non-extensible object's prototype is immutable: var fixed = object.preventextensions({}); // throws a 'typeerror'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return it. object.preventextensions(1); // typeerror: 1...
Proxy() constructor - JavaScript
ls to the underlying target object. handler.apply() a trap for a function call. handler.construct() a trap for the new operator. handler.defineproperty() a trap for object.defineproperty. handler.deleteproperty() a trap for the delete operator. handler.get() a trap for getting property values. handler.getownpropertydescriptor() a trap for object.getownpropertydescriptor. ...
... handler.apply() a trap for a function call. handler.construct() a trap for the new operator. handler.defineproperty() a trap for object.defineproperty. handler.deleteproperty() a trap for the delete operator. handler.get() a trap for getting property values. handler.getownpropertydescriptor() a trap for object.getownpropertydescriptor. handler.getprototypeof() a trap for object.getprototypeof. handler.has() a trap for the in operator. handler.isextensible() a trap for object.isextensible. handler.ownkeys() a trap for object.getownpropertynames and object.getownpropertysymbols. handler.preventextensions() a trap for object.preventextensions. handler.set() a trap for setting property values. handler.setprototypeof() a trap for object.setprototypeof. examples selectively...
Reflect.apply() - JavaScript
unction to call. thisargument the value of this provided for the call to target. argumentslist an array-like object specifying the arguments with which target should be called. return value the result of calling the given target function with the specified this value and arguments. exceptions a typeerror, if the target is not callable. description in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75]); with reflect.apply() this becomes less verbose and easier to understand. examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101...
...s value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75]); with reflect.apply() this becomes less verbose and easier to understand. examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111]) // "hello" reflect.apply(regexp.prototype.exec, /ab/, ['confabulation']).index // 4 reflect.apply(''.charat, 'ponies', [3]) // "i" specifications specification ecmascript (ecma-262)the definition of 'reflect.apply' in that specification. ...
Reflect.has() - JavaScript
value a boolean indicating whether 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. ...
... in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns true for any inherited properties, like the in operator: const a = {foo: 123} const b = {__proto__: a} const c = {__proto__: b} // the prototype chain is: c -> b -> a reflect.has(c, 'foo') // true specifications specification ecmascript (ecma-262)the definition of 'reflect.has' in that specification. ...
Symbol.isConcatSpreadable - JavaScript
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. description the @@isconcatspreadable symbol (symbol.isconcatspreadable) can be defined as an own or inherited property and its value is a boolean. ...
... avoid flattening in these cases. for array-like objects, the default behavior is no spreading or flattening. symbol.isconcatspreadable can force flattening in these cases. ...
Symbol.replace - JavaScript
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. ...
... 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. ...
Symbol.split - JavaScript
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. ...
... 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. ...
Symbol.unscopables - JavaScript
to false will make it scopable and thus it will appear in lexical scope variables. property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below. ...
...urable no examples scoping in with statements the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environment "keys" would now be the method and not the variable. that's when the unscopables symbol was introduced. a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] unscopables in objects you can also set unscopables for your own objects. var obj =...
WeakMap - JavaScript
e key has not been garbage collected. because the references are weak, weakmap keys are not enumerable. there is no method to obtain a list of the keys. if they were, the list would depend on the state of garbage collection, introducing non-determinism. if you want to have a list of keys, you should use a map. constructor weakmap() creates a new weakmap object. ...
...weakmap keys are not enumerable. there is no method to obtain a list of the keys. if they were, the list would depend on the state of garbage collection, introducing non-determinism. if you want to have a list of keys, you should use a map. constructor weakmap() creates a new weakmap object. instance methods weakmap.prototype.delete(key) removes any value associated to the key. weakmap.prototype.has(key) will return false afterwards. weakmap.prototype.get(key) returns the value associated to the key, or undefined if there is none. weakmap.prototype.has(key) returns a boolean asserting whether a value has been associated to the key in the weakmap object or not. weakmap.prototype.set(key, value) sets the value for the key in the weakmap object. returns the weakmap object. examples ...
WebAssembly.Table - JavaScript
ure representing a webassembly table, which stores function references. a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. note: tables can currently only store function references, but this will likely be expanded in the future. constructor webassembly.table() creates a new table object. instance properties table.prototype.length returns the length of the table, i.e. the number of elements. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a new webassembl...
...pecified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.was...
Iteration protocols - JavaScript
avascript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct. some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not. in order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that returns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the...
... user-defined iterables you can make your own iterables like this: let myiterable = {}; myiterable[symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; console.log([...myiterable]); // [1, 2, 3] built-in apis accepting iterables there are many apis that accept iterables. some examples include: new map([iterable]) new weakmap...
Lexical grammar - JavaScript
our hexadecimal digits following \u. it represents a code unit in the utf-16 encoding. for code points u+0000 to u+ffff, the code unit is equal to the code point. code points u+10000 to u+10ffff require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point. see also string.fromcharcode() and string.prototype.charcodeat(). '\u00a9' // "©" (u+a9) unicode code point escapes a unicode code point escape consists of \u{, followed by a code point in hexadecimal base, followed by }. the value of the hexadecimal digits must be in the range 0 and 0x10ffff inclusive. code points in the range u+10000 to u+10ffff do not need to be represented as a surrogate pair. code point escapes were added to javascript in...
... a unicode code point escape consists of \u{, followed by a code point in hexadecimal base, followed by }. the value of the hexadecimal digits must be in the range 0 and 0x10ffff inclusive. code points in the range u+10000 to u+10ffff do not need to be represented as a surrogate pair. code point escapes were added to javascript in ecmascript 2015 (es6). see also string.fromcodepoint() and string.prototype.codepointat(). '\u{2f804}' // cjk compatibility ideograph-2f804 (u+2f804) // the same character represented as a surrogate pair '\ud87e\udc04' regular expression literals see also regexp for more information. /ab+c/g // an "empty" regular expression literal // the empty non-capturing group is necessary // to avoid ambiguity with single-line comments. /(?:)/ template literals see also temp...
Destructuring assignment - JavaScript
ue" combined array and object destructuring array and object destructuring can be combined. ...
...name property in the object, you can do the following: const props = [ { id: 1, name: 'fizz'}, { id: 2, name: 'buzz'}, { id: 3, name: 'fizzbuzz'} ]; const [,, { name }] = props; console.log(name); // "fizzbuzz" the prototype chain is looked up when the object is deconstructed when deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain. let obj = {self: '123'}; obj.__proto__.prot = '456'; const {self, prot} = obj; // self "123" // prot "456"(access to the prototype chain) specifications specification ecmascript (ecma-262)the definition of 'destructuring assignment' in that specification. ...
super - JavaScript
super.prop = 2; // cannot overwrite the value. } } var y = new y(); y.foo(); // typeerror: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation. in this example, two objects define a method. in the second object, super calls the first object's method. ...
...alue. } } var y = new y(); y.foo(); // typeerror: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation. in this example, two objects define a method. in the second object, super calls the first object's method. this works with the help of object.setprototypeof() with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1. var obj1 = { method1() { console.log('method 1'); } } var obj2 = { method2() { super.method1(); } } object.setprototypeof(obj2, obj1); obj2.method2(); // logs "method 1" specifications specification ecmascript (ecma-262)the definition of 'super' in that specification. ...
Transitioning to strict mode - JavaScript
ted effect. if you really want to set a value to the global object, pass it as an argument and explicitly assign it as a property: var global = this; // in the top-level context, "this" always // refers to the global object function f(x) { 'use strict'; var a = 12; global.b = a + x * 35; } f(42); trying to delete a non-configurable property 'use strict'; delete object.prototype; // error! in non-strict, this would silently fail, in contradiction with the user expectation. poisoned arguments and function properties accessing arguments.callee, arguments.caller, anyfunction.caller, or anyfunction.arguments throws an error in strict mode. the only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = doc...
... ...
JavaScript
functional programming) styles. read more about javascript. ...
...res overview of available data structures in javascript. equality comparisons and sameness javascript provides three different value-comparison operations: strict equality using ===, loose equality using ==, and the object.is() method. closures a closure is the combination of a function and the lexical environment within which that function was declared. advanced inheritance and the prototype chain explanation of the widely misunderstood and under-estimated prototype-based inheritance. strict mode strict mode defines that you can not use any variable before initializing it. it is a restricted variant of ecmascript 5, for faster performance and easier debugging. javascript typed arrays javascript typed arrays provide a mechanism for accessing raw binary data. memory management m...
Exported WebAssembly functions - WebAssembly
ou call them, you get some activity in the background to convert the arguments into types that wasm can work with (for example converting javascript numbers to int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to javascript. you can retrieve exported webassembly functions in two ways: by calling table.prototype.get() on an existing table. by accessing a function exported from a wasm module instance via instance.exports. either way, you get the same kind of wrapper for the underlying function. from a javascript point of view, it's as if every wasm function is a javascript function too — but they are encapsulated by the exported wasm function object instance and there are only limited ways to access...
...via tbl.get() and log the result of invoking each one to the console. next, we use set() to make the othertable table contain references to the same functions as the tbl table. to prove this, we then retrieve these references back from othertable and print their results to console too, which gives the same results. they are real functions in the previous example, the return value of each table.prototype.get() call is an exported webassembly function — exactly what we have been talking about. it is worth noting that these are real javascript functions, in addition 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 f...
Content Processes - Archive of obsolete content
the postmessage function. this function uses the same pipe internally, and causes a 'message' event to be emitted on the other side. as explained earlier, firefox doesn't yet use separate processes for tabs or add-ons, so instead, each content script is loaded in a sandbox. sandboxes were explained this article. accessing the dom the global for the content sandbox has the window object as its prototype. this allows the content script to access any property on the window object, even though that object lives outside the sandbox. recall that the window object inside the sandbox is actually a wrapper to the real object. a potential problem with the content script having access to the window object is that a malicious page could override methods on the window object that it knows are being...
Modules - Archive of obsolete content
a.js", { loadscript: loadscript }).foo; => 5 // a.js: exports.foo = imports.loadscript("www.foo.com/b.js").bar; // b.js: exports.bar = 5; sandboxes and compartments the loadscript function as defined in the previous section still has some serious shortcomings. the object it passed to the loadsubscript function is an ordinary object, which has the global object of the loading script as its prototype. this breaks encapsulation, as it allows the script being loaded to access the built-in constructors of the loading script, which are defined on its global object. the problem with breaking encapsulation like this is that malicious scripts can use it to get the loading script to execute arbitrary code, by overriding one of the methods on the built-in constructors. if the loading script has chrome...
Guides - Archive of obsolete content
filing a patch, getting reviews, and getting help. modules learn about the module system used by the sdk (which is based on the commonjs specification), how sandboxes and compartments can be used to improve security, and about the built-in sdk module loader, known as cuddlefish. classes and inheritance learn how classes and inheritance can be implemented in javascript, using constructors and prototypes, and about the helper functions provided by the sdk to simplify this. private properties learn how private properties can be implemented in javascript using prefixes, closures, and weakmaps, and how the sdk supports private properties by using namespaces (which are a generalization of weakmaps). content processes the sdk was designed to work in an environment where the code to manipulat...
lang/functional - Archive of obsolete content
rint message is displayed since the function isn't executed parameters fn : function the function that will be executed only once inside the once wrapper. returns function : the wrapped fn that can only be executed once. chain(fn) creates a version of the input function that will return this. let { chain } = require("sdk/lang/functional"); function person (age) { this.age = age; } person.prototype.happybirthday = chain(function () this.age++); let person = new person(30); person .happybirthday() .happybirthday() .happybirthday() console.log(person.age); // 33 parameters fn : function the function that will be wrapped by the chain function. returns function : the wrapped function that executes fn and returns this. cache() an alias for once. debounce(fn, wait) this functio...
lang/type - Archive of obsolete content
defined, number, boolean, or string. returns false if value is not a primitive value. let { isprimitive } = require('sdk/lang/type'); isprimitive(3); // true isprimitive('foo'); // true isprimitive({}); // false parameters value : mixed the variable to check. returns boolean : boolean indicating if value is a primitive. isflat(value) returns true if value is a direct descendant of object.prototype or null. similar to jquery's isplainobject. let { isflat } = require('sdk/lang/type'); isflat({}); // true isflat(new type()); // false function type () {} parameters value : mixed the variable to check. returns boolean : boolean indicating if value is a direct descendant of object.prototype or null. isempty(value) returns true if value is an object with no properties and false otherwis...
Creating Event Targets - Archive of obsolete content
however: we're now importing from four modules: event/core gives us emit(): note that we don't need on, once, or off, since we will use eventtarget for adding and removing listeners event/ta...
Examples and demos from articles - Archive of obsolete content
lem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html] this example shows how to determine wh...
JS XPCOM - Archive of obsolete content
t, where as instanceof returns a boolean. xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm. components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); const cc = components.classes; const ci = components.interfaces; function abouthandler() {} abouthandler.prototype = { newchannel: function(uri) { var channel = services.io.newchannel("chrome://mystuff/content/mystuff.xul", null, null); channel.originaluri = uri; return channel; }, geturiflags: function(uri) { // do not return ci.nsiaboutmodule.uri_safe_for_untrusted_content unless // you make sure to set a non-system principal in newchannel. return ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
e this: interface myilocation : nsisupports { readonly attribute nsifile locationfile; }; place the idl file in the public/ directory of your project or subproject. in the src/ directory, place the javascript file that implements the component. ...
Custom about: URLs - Archive of obsolete content
factory = new factory(aboutcustom); // ... } and then on shutdown of your bootstrapped addon make sure to destroy the factory: function shutdown(adata, areason) { if ...
Enhanced Extension Installation - Archive of obsolete content
rce structure the extension manager implements a rdf datasource which contains a composite of the two xml/rdf datasources at the two install locations. the composite datasource handles all read-only information requests, and when data must be written the extension manager determines the appropriate datasource to write and flush to. ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
n's aren't necessarily fair, because we're not comparing apples to apples-- we're comparing an old design using html, tables, and spacer gifs to a new design much richer in imagery and style. what made you decide to drop tables as a layout mechanism? it seems like most designers think that you have to have at least some tables for layout. i've been manually writing sample code for my own design prototypes for 4 or 5 years now. i used to pride myself in knowing how to reproduce any interface design down to a pixel-perfect level. a developer would tell me something wasn't possible, and i could prove otherwise every time. like other designers and html whizzes, i became a master at manipulating and troubleshooting tables, nesting them in intricate ways to produce any layout or effect that could be im...
Visualizing an audio spectrum - Archive of obsolete content
imit < buffersize ) { for ( var i = 0; i < limit; i++ ) { this.reversetable[i + limit] = this.reversetable[i] + bit; } limit = limit << 1; bit = bit >> 1; } for ( var i = 0; i < buffersize; i++ ) { this.sintable[i] = math.sin(-math.pi/i); this.costable[i] = math.cos(-math.pi/i); } }; fft.prototype.forward = function(buffer) { var buffersize = this.buffersize, costable = this.costable, sintable = this.sintable, reversetable = this.reversetable, real = this.real, imag = this.imag, spectrum = this.spectrum; if ( buffersize !== buffer.length ) { throw "supplied buffe...
Basics - Archive of obsolete content
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! class console writes some information to the error console. you can find the console in the extra menu of firefox. the namespace for this api is console. methods info()this method does stuff. log(stringstring)this method writes a notification message to the console. stringthe message to add to the consolestring console.log("hello world!"); arn()this method does stuff. error()this method does stuff. exception()this method does stuff. logfromcaller()this method does stuff. ...
Page modifications - Archive of obsolete content
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! this documentation is under development. ...
Content - 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! page modifications greasemonkey! execute callbacks when certain pages are opened siteboost allows a jetpack to empower a domain with extended abilities beyond those native to web pages ...
Extenders - 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! manifest chief mechanism for allowing advanced api use within your jetpack superpowers similar to libraries, superpowers are for adding deeper platform coupling for your jetpack sandboxes safely abstracts library interoperability issues so you don't have to worry about them future api interface method for including not yet finalized functionality in your jetpack ...
Twitter - Archive of obsolete content
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! jetpack's twitter library, jetpack.lib.twitter, is a very simple, lightweight layer on top of twitter's rest api. in fact it's hardly more than syntactic sugar for doing xmlhttprequests. to use this library, you therefore need to be familiar with twitter's own api. (it's easy!) methods each method in twitter's api maps to a method here. for example, the twitter method for tweeting, statuses/update, maps to jetpack.lib.twitter.statuses.update(). to call trends/current, use jetpack.lib.twitter.trends.current(). ...
Libraries - Archive of obsolete content
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! namespace: jetpack.lib jetpack provides libraries for interacting with web and other services not part of the jetpack core. they live in the jetpack.lib namespace. ...
First run - Archive of obsolete content
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! jetpack lets you specify arbitrary content that will be shown to your users when they install your jetpack. you can also register a callback that will be called after installation. first-run page when users install your jetpack, they will be greeted with a new page notifying them that installation was successful. by default this page contains some simple text explaining that they may now use the jetpack and how to uninstall it. you can replace this text with a page tailored to your jetpack. ...
Enabling Experimental Jetpack Features - Archive of obsolete content
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! the proposed method for accessing jetpack features that are still in development and may be added in the future is inspired by python's future module. in python, you can call from __future__ import foo which adds the functionality that foo yields to the script. in jetpack, we propse adding a new function to the base namespace called importfromfuture. methods import(stringmountpath string)imports the requested experimental feature into the script. ...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
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! the jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); methods onfirstrun(funcfunction)jetpack.me.onfirstrun() allows jetpacks to be notified after they are successfully installed. onfirstrun() accepts a callback which is called after installation. ...
Meta - Archive of obsolete content
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! future imports experimental new language and api features. used often. ...
Jetpack Snippets - Archive of obsolete content
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! bits of code that may come in handy. ...
File access - 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! click on the paper-clip icon below for a demonstration of the file upload dialog. ...
Settings - Archive of obsolete content
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! the jetpack.storage.settings namespace allows jetpacks to specify user-configurable settings. jetpack will automatically generate a user interface based on the specification. the settings persist across browser sessions and are stored using the jetpack simple storage api. settings are private to each jetpack and are not accessible by other jetpacks. ...
Simple Storage - Archive of obsolete content
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! the jetpack.storage.simple namespace provides an easy way to persist data across browser restarts. it's a simple key-based persistent object data store. simple storage is really simple. jetpack.storage.simple is a single, persistent javascript object private to each jetpack. for the most part this object is like any other javascript object, and a jetpack can set whatever properties it wants on it. to manipulate its persistent data, a jetpack therefore need only use the various standard javascript functions and operators. ...
Storage - 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! simple storage an easy-to-use persistent object data store file access interface for performing file i/o settings settings persist across browser sessions and are accessible to jetpacks via simple object retrieval and assignment. ...
Clipboard - Archive of obsolete content
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! jetpack's clipboard support api provides a standardized way for features to access the clipboard. features can get and set the clipboard in various flavors of data type. the namespace associated with this api is jetpack.clipboard which provides both read and write access to the clipboard. the api is fairly straightforward; examples can be found here. the api lives in the future and must be imported for use. ...
System information - Archive of obsolete content
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! this documentation is under development. ...
System - Archive of obsolete content
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! clipboard interactions with the os clipboard system information get information about the platform on which jetpack is running visual effects os-level visual effects abilities devices methods for accessing and controlling devices (ex. ...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
please see the wiki page and online documentation for more information on how to use the add-on sdk. jetpack's menu api allows features to access and modify the browser's built-in menus. features can also create new menus and attach them almost anywhere, chrome or content, as popup menus or context menus. two namespaces are associated with this api: jetpack.menu, which provides access to the browser's menus, and jetpack.menu, the constructor for making new menus. the api is fairly comprehensive, so you may want to start by reading through some examples. ...
Notifications - Archive of obsolete content
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! the notification box appears at the bottom right corner of the browser and displays important information to the user. the namespace for this class is jetpack.notifications. methods show(titlestring, [body as string] iconstring)draws a notification box. ...
Panel - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Panel
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! please refer to the panels jep. ...
Selection - Archive of obsolete content
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! jetpack's selection api provides a method for detecting the selections made by the user. features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user. ...
Tabs - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Tabs
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. ...
slideBar - Archive of obsolete content
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! slidebar is a reinvention of the old sidebar features of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected its contents will be revealed from behind the current webpage. it currently under development and lives in the future. ...
UI - 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! menu accessing, modifying, and creating menus in the browser slidebar ui mechanism for displaying jetpack content in a slide-out animated vertical column toolbar including entries and access elements into the toolbar panel a movable, expandable, and custom styled content element to display jetpack content tabs adding events and interacting with browser tabs and their contained documents statusbar low-level functions and basic calls notifications a system for alerting use...
Supporting private browsing mode - Archive of obsolete content
that is sent when the browser purges private data that extensions can watch in order to know when it's time to do the same. a private browser listener helper object this helper object registers listeners for private browsing mode changes. this handles interacting with the private browsing service so you don't have to. ...
Tamarin build documentation - Archive of obsolete content
m/unix $ make the resulting executable "shell" is built in the current directory. compiling and running applications currently the only compiler for tamarin is the adobe actionscript compiler. the source code for the actionscript compiler, asc, has been open sourced as part of adobe flex®. this compiler is written in java and will require the installation of a java™ 1.4 or later jdk. a prototype self-hosting ecmascript edition 4 compiler, esc, is provided with tamarin but it is not yet capable of bootstrapping itself or building applications. esc is under active development and will be able to generate tamarin applications later this year. use the following steps to build and install the actionscript compiler. download and build the asc source code using the subversion client $ sv...
The new nsString class implementation (1999) - Archive of obsolete content
even though there is a performance penalty for doing so. since i have to acknowledge the idiom, i have made nscstring available but note that it should be used sparingly. memory management a principal enhancement of the new architecture is pluggable memory allocators. all nsstring subclasses provide their own default allocator implementations, but programmers are free to use their own. in the new prototype nsstrimpl and nsstring classes, the allocator is an intrinsic member installed during construction of the string (by default they share a global allocator). note: the com rules imply that everyone needs to use the same allocators, that they acquire via a global com service called cogetmalloc(). our nsstrimpl uses an allocator pattern so that programmers can install their own policy, but this may ...
Venkman Internals - Archive of obsolete content
]); where |pc| is the program counter location to set the breakpoint, and |parentbp| is an optional "future breakpoint" object to use as the parent for this breakpoint. if you set the breakpoint right from the jsdscript instead, you wouldn't see it in the venkman ui, and you might confuse venkman when the actual breakpoint was hit and it couldn't find a matching breakpoint object. you can see the prototype for this object at http://lxr.mozilla.org/mozilla/sourc...ebugger.js#914 scriptwrapper.jsdscript is the reference to the jsdiscript object for the function. sourcecontext is the 5 lines of source text before the last instance of the word "function" on the line where this function starts. (not in 2006, seems to be computed on the fly in getsourcecontext()). the full text of the file can be found i...
Providing Command-Line Options - Archive of obsolete content
specifying the uri of the window to open. ...
CommandLine - Archive of obsolete content
sicategorymanager); catman.deletecategoryentry("command-line-handler", cld_category); }, canunload : function (acompmgr) { return true; } }; function nsgetmodule(acompmgr, afilespec) { return apphandlermodule; } create an observer that will get notified when arguments change: chrome/content/cmdline.js function commandlineobserver() { this.register(); } commandlineobserver.prototype = { observe: function(asubject, atopic, adata) { var cmdline = asubject.queryinterface(components.interfaces.nsicommandline); var test = cmdline.handleflagwithparam("test", false); alert("test = " + test); }, register: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interf...
xbDesignMode.js - Archive of obsolete content
s.meditordocument = this.miframeelement.contentdocument; this.meditordocument.designmode = "on"; } else { // ie this.meditordocument = this.miframeelement.contentwindow.document; this.meditordocument.designmode = "on"; // ie needs to reget the document element after designmode was set this.meditordocument = this.miframeelement.contentwindow.document; } } xbdesignmode.prototype.execcommand = function (acommandname, aparam){ if (this.meditordocument) this.meditordocument.execcommand(acommandname, false, aparam); else throw "no meditordocument found"; } xbdesignmode.prototype.setcsscreation = function (ausecss){ if (this.meditordocument) this.meditordocument.execcommand("usecss", false, ausecss); else throw "no meditordocument found"; } ...
Monitoring plugins - Archive of obsolete content
observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class below is a skeleton class that you may use to listen to runtime notifications: function pluginobserver() { this.registered = false; this.register(); //takes care of registering this class with observer services as an observer for plugin runtime notifications } pluginwatcherobserver.prototype = { observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call") //in case your class is registered to listen to other topics //this gets executed each time a runtime notification arrives // --your code goes here-- } }, //takes care of registering the observer services for the "experimental-notify-plugin-call" topic register: fu...
NPN_SetValue - Archive of obsolete content
unload the dll and not to call np_shutdown when the page is left. in such a case all this will be done on the browser shutdown. the plugin calls npn_setvalue any time with nppvpluginkeeplibraryinmemory as variable parameter and value set to true. by default, the dll will be unloaded from memory preceded by an np_shutdown call. remarks all four variable values are boolean. although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. the browser code reads this parameter as follows (nppvpluginwindowbool as an example): nperror np_export _setvalue(npp npp, nppvariable variable, void *value) { ... bool bwindowless = (value == null); ... } so the proper way to call this function from a plug-in would be: bool bwindowed = false;...
E4X for templating - Archive of obsolete content
g, '&apos;'); } 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). ...
The global XML object - Archive of obsolete content
« previous the global xml object e4x-capable javascript engines put a new property on the global object. the xml object has several properties that allow you to customize parsing and serialization of e4x. xml elements will remember the settings of the xml object from the time of their creation. extending xml.prototype xml.prototype and xmllist.prototype (xmllist.prototype is actually just xml.prototype) cannot be extended in the same conventional way as other constructors such as object. you can only define methods in xml.prototype and not fields. to add a method to xml.prototype, define xml.prototype.function::methodname or xml.prototype.function::[methodnamestring]. the following example defines the foocount() method, which returns the amount of <foo> elements in the xml: xml.proto...
Array.observe() - Archive of obsolete content
type. the index at which the change occurred. removed: only for the "splice" type. an array of the removed elements. addedcount: only for the "splice" type. the number of elements added. description the callback function is called each time a change is made to arr, with an array of all changes in the order in which they occurred. changes done via array methods, such as array.prototype.pop() will be reported as "splice" changes. index assignment changes which do not change the length of the array may be reported as "update" changes. examples logging different change types var arr = ['a', 'b', 'c']; array.observe(arr, function(changes) { console.log(changes); }); arr[1] = 'b'; // [{type: 'update', object: <arr>, name: '1', oldvalue: 'b'}] arr[3] = 'd'; // [{type: 'splic...
ArrayBuffer.transfer() - Archive of obsolete content
ce must be an instance of arraybuffer'); if (length <= source.bytelength) return source.slice(0, length); var sourceview = new uint8array(source), destview = new uint8array(new arraybuffer(length)); destview.set(sourceview); return destview.buffer; }; } specifications specification status comment arraybuffer.prototype.transfer proposal draft stage 2 draft ...
Array comprehensions - Archive of obsolete content
obsolete since gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55)this 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. the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one. ...
Function.arity - Archive of obsolete content
specifications not part of any standard. ...
New in JavaScript 1.1 - Archive of obsolete content
oduced javascript language versions. <script language="javascript"> <!-- javascript for navigator 2.0. --> <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> new features in javascript 1.1 new objects array boolean function number new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect. communication between java and javascript. 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(...
New in JavaScript 1.5 - Archive of obsolete content
t 1.5. this version was included in netscape navigator 6.0 was released on november 14, 2000 and was also used in later versions of netscape navigator and firefox 1.0. you can compare javascript 1.5 to jscript version 5.5 and internet explorer 5.5, which was released in july 2000. the corresponding ecma standard is ecma-262 edition 3 (from december 1999). new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word. multiple catch clauses in a try...catch statement are supported. javascript authors can now add getters and setters to their objects. changed functionality in javascript 1.5 runtime errors are now reported as exceptions. regular expression changes: quantifiers — +, *, ? and {...
New in JavaScript 1.6 - Archive of obsolete content
ovember 2005. the corresponding ecma standard is ecma-262 edition 3 and ecmascript for xml (e4x) with some additional features. several new features were introduced: e4x, several new array methods, and array and string generics. new features in javascript 1.6 support for ecmascript for xml (e4x) for creating and processing xml content within javascript has been added. see for details. array.prototype.indexof() array.prototype.lastindexof() array.prototype.every() array.prototype.filter() array.prototype.foreach() array.prototype.map() array.prototype.some() array generics string generics for each...in changed functionality in javascript 1.6 a bug in which arguments[n] cannot be set if n is greater than the number of formal or actual parameters has been fixed. ...
New in JavaScript 1.8.1 - Archive of obsolete content
the following is a changelog for javascript 1.8.1. this version was included in firefox 3.5. javascript 1.8.1 is a modest update syntactically to javascript; the main change in this release is the addition of the tracemonkey just-in-time compiler, which improves performance. new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript. this makes the behavior of setting the values of properties more predictable. ...
New in JavaScript 1.8 - Archive of obsolete content
cifying the javascript version. new features in javascript 1.8 expression closures. generator expressions. allowing you to simply create generators (which were introduced in javascript 1.7). typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement. array.prototype.reduce() array.prototype.reduceright() changed functionality in javascript 1.8 changes in destructuring for..in one change that occurred in the release of javascript 1.8 was a bug fix related to the key/value destructuring of arrays introduced in javascript 1.7. previously it was possible to destructure the keys/values of an array by using for ( var [key, value] in array ). however, that mad...
ECMAScript 5 support in Mozilla - Archive of obsolete content
ipt 5.1 features. this article covers the features supported by different versions of mozilla's javascript runtime. supported features added in javascript 1.8.5 (gecko 2, firefox 4 and later) firefox 4 has full ecmascript 5 support including the object.* methods and strict mode. see new in javascript 1.8.5. added in javascript 1.8.1 (gecko 1.9.1, firefox 3.5) native json support object.getprototypeof() method. string.trim() method, which trims whitespace from both ends of the string. gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5. improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents evaluating xhtml as javascript code in certain circumstances. added in javascript 1.6 (gecko 1.8, firefox 1.5) new arr...
forEach - Archive of obsolete content
plementation to throw errors if wrong arguments are provided and implement this in fewer lines of code. i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. dotnetcarpenter 30 june 2012 <hr> i have released the write access restriction, but i will be watching changes closely. jswisher 01 october 2011 <hr> there is some mistype in array.prototype.foreach: kvalue = o[ pk ]; should be kvalue = o[ k ]; <hr> this page has been the target of a revert war, and so write access to it has been restricted. if you wish to make changes, and especially if you wish to revert another user's changes, please either add a comment here, or post to dev-mdc@lists.mozila.org, explaining the change you desire. jswisher 15 aug 2011 <hr> is this a from _core_ o...
Writing JavaScript for XHTML - Archive of obsolete content
gh it is compatible with xhtml 1.0, is not guaranteed to work with future versions of xhtml (perhaps especially the formatting properties which have been deprecated as element attributes). the regular xml dom provides sufficient methods via the element interface for getting/setting/removing attributes. problem: my favourite js library still breaks if you use javascript libraries like the famous prototype.js or yahoo's one, there is bad news for you: as long as the developers don't apply the fixes mentioned above, you won't be able to use them in your xml-xhtml applications. two possible ways still are there, but neither is very promissing: take the library, recode it and publish it or e-mail the developers, e-mail your friends to e-mail the developers and e-mail your customers to e-mail the deve...
Index - Game development
start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl. this article explains how to get up and running with a-frame, and how to use it to build up a simple demo. 17 building up a basic demo with babylon.js 3d game engines, babylon.js, beginner, webgl babylon.js is one of the most popular 3d game engines used by developers. as with any other 3d library it provides bu...
Bounding volume collision detection with THREE.js - Game development
rsphere); sphere vs. box3 unfortunately this test is not implemented in three.js, but we can patch sphere to implement a sphere vs. aabb intersection algorithm. ...
Building up a basic demo with A-Frame - Game development
start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl. this article explains how to get up and running with a-frame, and how to use it to build up a simple demo. high level overview the current version of a-frame is 0.3.2, which means it's highly experimental, but it already works and you can test it right away in the browser. it runs on desktop, mobile (ios and android), and oculus r...
Building up a basic demo with PlayCanvas editor - Game development
anel, select the script option, and name your new script file boxanimation.js. if you double click on it, you'll be moved to a code editor. ...
Efficient animation for web games - Game development
lar frame. requestanimationframe causes the browser to redraw and call your function before that frame gets to the screen. the downside of using this vs. settimeout is that your animations must be time-based instead of frame-based, i.e. you must keep track of time and set your animation properties based on elapsed time. requestanimationframe includes a domhighrestimestamp in its callback function prototype, which you definitely should use (as opposed to using the date object), as this will be the time the frame began rendering, and ought to make your animations look more fluid. you may have a callback that ends up looking something like this: var starttime = -1; var animationlength = 2000; // animation length in milliseconds function doanimation(timestamp) { // calculate animation progress va...
Class - MDN Web Docs Glossary: Definitions of Web-related terms
in object-oriented programming, a class defines an object's characteristics. ...
Inheritance - MDN Web Docs Glossary: Definitions of Web-related terms
ming. ...
OOP - MDN Web Docs Glossary: Definitions of Web-related terms
oop (object-oriented programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts. javascript is heavily object-oriented. it follows a prototype-based model (as opposed to class-based). learn more general knowledge object-oriented programming on wikipedia introduction to object-oriented javascript ...
Parent object - MDN Web Docs Glossary: Definitions of Web-related terms
the object to which a given property or method belongs. learn more discussion of inheritance and prototypes in javascript ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. there are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. there also is null, which is seemingly primitive, but indeed is a special case for every object: and any structured type is derived from null by the prototype chain. most of the time, a primitive value is represented directly at the lowest level of the language implementation. all primitives are immutable, i.e., they cannot be altered. it is important not to confuse a primitive itself with a variable assigned a primitive value. the variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. example t...
Type - MDN Web Docs Glossary: Definitions of Web-related terms
if you are unsure of the type of a value, you can use the typeof operator. ...
MDN Web Docs Glossary: Definitions of Web-related terms
png polyfill polymorphism pop3 port prefetch preflight request prerender presto primitive privileged privileged code progressive enhancement progressive web apps promise property property (css) property (javascript) protocol prototype prototype-based programming proxy server pseudo-class pseudo-element pseudocode public-key cryptography python q quality values quaternion quic r rail random number generator raster image rdf real user monitoring (rum) recu...
Supporting older browsers - Learn web development
e time of writing, this is mostly an issue with internet explorer 10, which uses the -ms- prefix for flexbox. this also means that there are some outdated articles and tutorials in existence; this useful guide helps you check what you are looking at and can also help if you need flex support in very old browsers. the ie10 and 11 prefixed version of grid the css grid specification was initially prototyped in internet explorer 10; this means that while ie10 and ie11 do not have modern grid support, they do have a version of grid layout that is very usable, although different to the modern specification documented on this site. the ie10 and 11 implementations is -ms- prefixed, which means you can use it for these browsers and it will be ignored by non-microsoft browsers. edge does still understand...
Example 3 - Learn web development
adius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activesele...
Example 4 - Learn web development
adius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activesele...
Example 5 - Learn web development
adius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activesele...
How to build custom form controls - Learn web development
ning before starting. the object returned by the queryselectorall() function is a nodelist rather than an array. this is important because array objects support the foreach function, but nodelist doesn't. because nodelist really looks like an array and because foreach is so convenient to use, we can easily add the support of foreach to nodelist in order to make our life easier, like so: nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } if you need to support legacy browsers, ensure the browsers support these features. if not, you can iterate through the list or you may need to use a library or pollyfill. building event callbacks the groundwork is done. we can now start to define all the functions that will be used each time the user interacts w...
Introducing asynchronous JavaScript - Learn web development
do they allow you to control the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. so you could have different actions to run on the response downloaded, such as processjson(), displaytext(), etc. note that not all callbacks are async — some run synchronously. an example is when we use array.prototype.foreach() to loop through the items in an array (see it live, and the source): const gods = ['apollo', 'artemis', 'ares', 'zeus']; gods.foreach(function (eachname, index){ console.log(index + '. ' + eachname); }); in this example we loop through an array of greek gods and print the index numbers and values to the console. the expected parameter of foreach() is a callback function, which itse...
Introduction to web APIs - Learn web development
they use events to handle changes in state we already discussed events earlier on in the course in our introduction to events article, which looks in detail at w...
Solve common problems in your JavaScript code - Learn web development
adding or removing elements) using javascript? ...
JavaScript object basics - Learn web development
er variables and functions that have the same names. objects let us keep the information safely locked away in their own package, out of harm's way. ...
Introducing JavaScript objects - Learn web development
of the features you've already dealt with are in fact objects. object-oriented javascript for beginners with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances. object prototypes prototypes are the mechanism by which javascript objects inherit features from one another, and they work differently to inheritance mechanisms in classical object-oriented programming languages. in this article, we explore that difference, explain how prototype chains work, and look at how the prototype property can be used to add methods to existing constructors. inheritance in javascript w...
Server-side web frameworks - Learn web development
back in the early days of the web, many people learned perl because of a wonderful perl library called cgi. it was simple enough to get started without knowing much about the language and powerful enough to keep you going. mojolicious implements this idea using bleeding edge technologies. some of the features provided by mojolicious are: a real-time web framework, to easily grow single-file prototypes into well-structured mvc web applications. restful routes, plugins, commands, perl-ish templates, content negotiation, session management, form validation, testing framework, static file server, cgi/psgi detection, and first-class unicode support. a full-stack http and websocket client/server implementation with ipv6, tls, sni, idna, http/socks5 proxy, unix domain socket, comet (long polling),...
Ember app structure and componentization - Learn web development
s left </span> <ul class="filters"> <li> <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> </section> the rendered output should now be as follows: this looks pretty complete, but remember that this is only a static prototype. now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app. looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the ui, but let's plan on splitting the html out into the following components: the component groupings are as follows: the main input / "new-todo" (red in the image) ...
Componentizing our React app - Learn web development
heck, if you’d like. note: all_caps constant names have no special meaning in javascript; they’re a convention that tells other developers "this data will never change after being defined here”. rendering with iteration to render our array of objects, we have to turn each one into a <todo /> component. javascript gives us an array method for transforming data into something else: array.prototype.map(). above the return statement of app(), make a new const called tasklist and use map() to transform it. let's start by turning our tasks array into something simple: the name of each task: const tasklist = props.tasks.map(task => task.name); let’s try replacing all the children of the <ul> with tasklist: <ul role="list" classname="todo-list stack-large stack-exception" aria-labell...
React interactivity: Events and state - Learn web development
tetask() is invoked correctly, we can call our settasks() hook in deletetask() to actually delete that task from the app’s state as well as visually in the app ui. since settasks() expects an array as an argument, we should provide it with a new array that copies the existing tasks, excluding the task whose id matches the one passed into deletetask(). this is a perfect opportunity to use array.prototype.filter(). we can test each task, and exclude a task from the new array if its id prop matches the id parameter passed into deletetask(). update the deletetask() function inside your app.js file as follows: function deletetask(id) { const remainingtasks = tasks.filter(task => id !== task.id); settasks(remainingtasks); } try your app out again. now you should be able to delete a task from yo...
Starting our Svelte Todo list app - Learn web development
handler(warning); } }), ... ] by design, these warnings are implemented in the compiler itself, and not as a plug-in that you may choose to add to your project. the idea is to check for a11y issues in your markup by default and let you opt-out of specific warnings. note: you should only disable these warnings if you have good reasons to do so, for example while building a quick prototype. it's important to be a good web citizen and make make your pages accessible to the broadest possible userbase. the accessibility rules checked by svelte are taken from eslint-plugin-jsx-a11y, a plugin for eslint that provides static checks for many accessibility rules on jsx elements. svelte aims to implement all of them in its compiler, and most of them have already been ported to svelte. on ...
Creating a Login Manager storage module
lowing code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface. see how_to_build_an_xpcom_component_in_javascript for more details about javascript components. ...
Creating Custom Events That Can Pass Data
ermanager::createevent() like this: if (aeventtype.lowercaseequalsliteral("nsmyevent")){ //note: the lowercase is important! nsdomevent* it = new nsdommyevent(aprescontext, aevent); if (nsnull == it) { return ns_error_out_of_memory; } return callqueryinterface(it, adomevent); } in general though i'd strongly recommend using a function the way that everyone else does. you can find the prototypes for the function in nsiprivatedomevent. your event in order for your event to work you must do the following: create a scriptable interface called nsidom{youreventname} inheriting from nsidomevent. a good place to put this .idl is in mozilla/dom/public/idl/events/. #include "nsidomevent.idl" [scriptable, uuid(08bea243-8a7b-4554-9ee9-70d7785d741b)] interface nsidommyevent: nsidomevent { //pu...
Communicating with frame scripts
r browsermm = gbrowser.selectedbrowser.messagemanager; browsermm.loadframescript("chrome://my-addon@me.org/content/frame-script.js", false); messagemanagers.push(browsermm); console.log(messagemanagers.length); we can listen for message-manager-disconnect to update the array when the message managers disconnect (for example because the user closed the tab): function myobserver() { } myobserver.prototype = { observe: function(subject, topic, data) { var index = messagemanagers.indexof(subject); if (index != -1) { console.log("one of our message managers disconnected"); mms.splice(index, 1); } }, register: function() { var observerservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); observerservice.addob...
Frame script loading and lifetime
et allowdelayedload, the script is loaded into a new tab as soon as it is created. frame scripts are associated with a browser tab and not with a page. so once you load them, they will stay loaded until the tab is closed, even if you reload the document or navigate. if you want to limit a script to the lifetime of a page you can create a sandbox instead, where the current content page is used as prototype. if you want a frame script to do something when a new document is loaded, you need to listen for an appropriate dom event, generally domwindowcreated, domcontentloaded, or load. unloading frame scripts frame scripts are automatically unloaded when their hosting tab is closed. there is currently no way to unload them when loaded, other than closing the tab they were loaded into. to listen for...
Performance
of script evaluation. delaying the script registration until the session is restored my provide some middle ground for some addons. it does not provide the same memory footprint reductions but it improves application startup. beam down information in advance to avoid synchronous calls to the parent bad: // processscript.js function contentpolicy() { // ... ...
OS.File.Info
global object os.file.info methods object tomsg(in os.file.info value) os.file.tomsg convert an instance of os.file.info to a form that can be serialized and transmitted between threads or processes. object tomsg( in os.file.info value ) arguments returns an object with the same fields as value but that may be serialize...
DMD
/memory/replace/dmd/dmd.cpp:1286) #02: malloc (/home/njn/moz/mi5/go64dmd/memory/build/../../../memory/build/replace_malloc.c:153) #03: moz_xmalloc (/home/njn/moz/mi5/memory/mozalloc/mozalloc.cpp:84) #04: nscyclecollectingautorefcnt::incr(void*, nscyclecollectionparticipant*) (/home/njn/moz/mi5/go64dmd/dom/xul/../../dist/include/nsisupportsimpl.h:250) #05: nsxulelement::create(nsxulprototypeelement*, nsidocument*, bool, bool,mozilla::dom::element**) (/home/njn/moz/mi5/dom/xul/nsxulelement.cpp:287) #06: nsxblcontentsink::createelement(char16_t const**, unsigned int, mozilla::dom::nodeinfo*, unsigned int, nsicontent**, bool*, mozilla::dom::fromparser) (/home/njn/moz/mi5/dom/xbl/nsxblcontentsink.cpp:874) #07: nscomptr<nsicontent>::startassignment() (/home/njn/moz/mi5/go64dmd/dom...
NSPR Contributor Guide
hood for acceptance. general guidelines downward compatibility because many different applications, besides the mozilla client, use the nspr api, the api must remain downward compatible across even major releases. this means that the behavior of an existing public api item in nspr cannot change. should you need to have a similar api, with some slightly different behavior or different function prototype, then suggest a new api with a different name. c language api the nspr api is a c language api. please do not contribute java, c or other language wrappers. coding style nspr does not have a documented coding style guide. look at the extant code. make yours look like that. some guidelines concerning naming conventions can be found in nspr naming conventions in the nspr reference. see also: ...
NSPR Poll Method
he protocol of that layer is implemented by a priomethods table. the bottom layer is a wrapper for the underlying network transport. the nspr library provides a reference implementation of the bottom layer using the sockets api, but you can provide your own implementation of the bottom layer using another network transport api. the poll method is one of the functions in the priomethods table. the prototype of the poll method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is already able to make progress in the manner suggested by the polling flags. the argu...
Optimizing Applications For NSPR
nt will be left with an invalid pointer to the child. the problem has a solution that will be available soon. digital unix digital unix (aka, osf1) requires the latest patches for the pthreads library. the changes are not evident until one tries to do thread suspension (<tt>pr_suspendall()</tt>) which is in preparation for garbage collection. digital unix is the main platform used for nspr's prototype use of ipv6. there are some conflicts between the patches needed to use ipv6 and those needed for pthreads. the ipv6 kit needs to be applied on a baseline configuration of digital unix v4.0b. linux the pthreads version of linux (which is not the default) uses the same signals that nspr uses to suspend threads in preparation for garbage collection. no solution in hand. os/2 the os/2 port i...
NSPR Types
ible functions and globals. algebraic types of various lengths are used for integer algebra. miscellaneous types are used for representing size, pointer difference, boolean values, and return values. for information on naming conventions for nspr types, functions, and macros, see nspr naming conventions. calling convention types these types are used to support cross-platform declarations of prototypes and implementations: pr_extern is used for declarations of external functions or variables. pr_implement is used for definitions of external functions or variables. pr_callback is used for definitions and declarations of functions that are called via function pointers. a typical example is a function implemented in an application but called from a shared library. here are some simple exam...
PR_EXTERN
for syntax details for each platform, see prtypes.h. the macro includes the proper specifications to declare the target extern and set up other required linkages. warning: some platforms do not allow the use of the underscore character (_) as the first character of an exported symbol. ...
Certificate functions
the public functions listed here are used to interact with certificate databases. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions cert_addcerttolisttail mxr 3.2 and later cert_addextension mxr 3.5 and later cert_addocspacceptableresponses mxr 3.6 and later cert_addokdomainname mxr 3.4 and later cert_addrdn mxr 3.2.1 and la...
Cryptography functions
the public functions listed here perform cryptographic operations based on the pkcs #11 interface. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions pk11_algtagtomechanism mxr 3.2 and later pk11_authenticate mxr 3.2 and later pk11_blockdata mxr 3.2 and later pk11_changepw mxr ...
Deprecated SSL functions
n replaced with newer versions. the deprecated functions are not supported by the new ssl shared libraries. applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below. each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. function name/documentation source code replacement in nss 3.2 ssl_enable mxr ssl_optionset ssl_enablecipher mxr ssl_cipherprefsetdefault ssl_enabledefault mxr ssl_optionsetdefault ssl_redohandshake mxr ssl_rehandshake ...
Index
it works by inserting a special set of entry points between nss and the module. 192 nss tech note3 no summary! 193 nss tech note4 no summary! 194 nss tech note5 note: aes encryption, a fixed blocksize of 16 bytes...
NSS Memory allocation
re are two consequences of the use of plarenapools that affect leak analysis. they are: 1. at the end of execution of a program, all the arenas in the free list will appear to have been leaked. this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list. there is a function named pl_arenafinish that really frees all the arenas on the free list. see the prototype at http://mxr.mozilla.org/nspr/source/n.../ds/plarenas.h a program should call that function at the very end, after having shutdown nss and nspr, to really free the contents of the free list. after that function returns, any arenas that still appear to be leaked have truly been leaked, and are not merely on the free list. 2. leak analysis tools will frequently report the wrong call stack for the ...
NSS_3.12.2_release_notes.html
aia extension is not used in some bridge ca / known certs configuration bug 437804: certutil -r for cert renewal should derive the subject from the cert if none is specified. bug 444974: crash upon reinsertion of e-identity smartcard bug 447563: modutil -add prints no error explanation on failure bug 448431: pk11_createmergelog() declaration causes gcc warning when compiling with -wstrict-prototypes bug 449334: pk12util has duplicate options letters bug 449725: signver is still using static libraries. bug 450427: add comodo ecc certification authority certificate to nss bug 450536: remove obsolete xp_mac code bug 451024: certutil.exe crashes with segmentation fault inside pr_cleanup bug 451927: security/coreconf/winnt6.0.mk has invalid defines bug 452751: slot leak in pk11_fin...
NSS 3.12.4 release notes
lve a few remaining issues with nss's new revocation flags bug 489710: byteswap optimize for msvc++ bug 490154: cryptokey framework requires module to implement generatekey when they support keypairgeneration bug 491044: remove support for vms (a.k.a., openvms) from nss bug 491174: cert_pkixverifycert reports wrong error code when ee cert is expired bug 491919: cert.h doesn't have valid functions prototypes bug 492131: a failure to import a cert from a p12 file leaves error code set to zero bug 492385: crash freeing named crl entry on shutdown bug 493135: bltest crashes if it can't open the input file bug 493364: can't build with --disable-dbm option when not cross-compiling bug 493693: sse2 instructions for bignum are not implemented on os/2 bug 493912: sqlite3_reset should be invoked in sdb_findo...
NSS 3.55 release notes
. bug 1647752 - update dtls 1.3 implementation to draft-38. bug 1649190 - run cipher, sdr, and ocsp tests under standard test cycle in ci. bug 1649226 - add wycheproof ecdsa tests. bug 1637222 - consistently enforce iv requirements for des and 3des. bug 1067214 - enforce minimum pkcs#1 v1.5 padding length in rsa_checksignrecover. bug 1643528 - fix compilation error with -werror=strict-prototypes. bug 1646324 - advertise pkcs#1 schemes for certificates in the signature_algorithms extension. bug 1652331 - update nss 3.55 nspr version to 4.27. this bugzilla query returns all the bugs fixed in nss 3.55: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.55 compatibility nss 3.55 shared libraries ...
NSS Developer Tutorial
ozilla c++ language features guide, and the chromium c++ usage guide, list c++ features that are known to be widely available and compatible. you should limit features to those that appear in both guides. ask on nss-dev@ if you think this is restrictive, or if you wish to prohibit a specific feature. nss c abi backward compatibility functions exported functions cannot be removed. the function prototype of an exported function, cannot be changed, with these exceptions: a foo * parameter can be changed to const foo *. this change is always safe. sometimes an int parameter can be changed to unsigned int, or an int * parameter can be changed to unsigned int *. whether such a change is safe needs to be reviewed on a case-by-case basis. types structs members of an exported struct, c...
nss tech note1
rences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. the main non-streaming apis for these two decoders have an identical prototype : secstatus sec_asn1decodeitem(prarenapool *pool, void *dest, const sec_asn1template *t, secitem *item); secstatus sec_quickderdecodeitem(prarenapool* arena, void* dest, const sec_asn1template* templateentry, secitem* src); here is a description of the arguments : secitem* src† is a structure containing a pointer to the binary data to be decoded, as well as its size. const sec_...
NSS PKCS11 Functions
(either a smart card or soft token) to access protected information, such as a private key. such information is protected with a password that can be retrieved by calling an application-supplied callback function. the callback function is identified in a call to pk11_setpasswordfunc that takes place during nss initialization. the callback function set up by pk11_setpasswordfunc has the following prototype: typedef char *(*pk11passwordfunc)( pk11slotinfo *slot, prbool retry, void *arg); this callback function has the following parameters: slot a pointer to a slot info structure. retry set to pr_true if this is a retry. this implies that the callback has previously returned the wrong password. arg a pointer supplied by the application that can be used to pass state information. can be null. t...
PKCS 12 functions
the nss version column indicates which versions of nss support the function. ...
PKCS 7 functions
the nss version column indicates which versions of nss support the function. ...
pkfnc.html
(either a smart card or soft token) to access protected information, such as a private key. such information is protected with a password that can be retrieved by calling an application-supplied callback function. the callback function is identified in a call to pk11_setpasswordfunc that takes place during nss initialization. the callback function set up by pk11_setpasswordfunc has the following prototype: typedef char *(*pk11passwordfunc)( pk11slotinfo *slot, prbool retry, void *arg); this callback function has the following parameters: slot a pointer to a slot info structure. retry set to pr_true if this is a retry. this implies that the callback has previously returned the wrong pas...
SSL functions
reference documents the functions most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (dxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions nss_getclientauthdata mxr 3.2 and later nss_setdomesticpolicy mxr 3.2 and later nss_setexportpolicy mxr 3.2 and later nss_setfrancepolicy mxr 3.2 and l...
S/MIME functions
the nss version column indicates which versions of nss support the function. ...
Utility functions
the public functions listed here perform initialization tasks and other services. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. function name/documentation source code nss versions atob_asciitodata mxr deprecated 3.2 use nssbase64_decodebuffer atob_convertasciitoitem mxr deprecated 3.2 use nssbase64_decodebuffer btoa_convertitemtoascii mxr deprecated 3...
Scripting Java
anywhere a java array of that type is allowed. js> a[0] = 104 104 js> a[1] = 105 105 js> new java.lang.string(a) hi java strings and javascript strings it's important to keep in mind that java strings and javascript strings are not the same. java strings are instances of the type java.lang.string and have all the methods defined by that class. javascript strings have methods defined by string.prototype. the most common stumbling block is length, which is a method of java strings and a dynamic property of javascript strings: js> javastring = new java.lang.string("java") java js> jsstring = "javascript" javascript js> javastring.length() 4 js> jsstring.length 10 rhino provides some help in reducing the differences between the two types. first, you can pass a javascript string to a java method ...
Exact Stack Rooting
u see a gcpointer stored as a private, please file a bug. the private field is frequently used to store things that are not gcpointers, so the gc cannot automatically handle this slot. this means it must be manually traced by the object's owner: this is both fragile and more expensive than using an extra reserved slot, or even just putting a new property on the object. class fooclass = { "fooprototype", /* name */ jsclass_has_private | jsclass_has_reserved_slots(1), /* flags */ js_propertystub, /* addproperty */ js_propertystub, /* delproperty */ ... etc ... }; rootedobject obj(cx, newobject(cx, &fooclass, nullptr(), nullptr(), &obj)); rootedvalue v(cx, object_to_value(othergcthing)); jsobject::setreservedslot(obj, 0, v); storing a gcpointer on the ch...
SpiderMonkey Internals
hese file pairs implement the standard classes and (where they exist) their underlying primitive types. they have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions. jsobj.*, jsscope.* these two pairs declare and implement the js object system. all of the following happen here: creating objects by class and prototype, and finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them. the details of a native object's map (scope) are mostly hidden in jsscope.[ch]. jsatom.cpp, jsatom.h the atom manager. contains well-known string constants, their atoms, the global atom hash table and related state, the js_atomize() function...
JS::CloneFunctionObject
t creates a new function object from funobj. the new object has the same code and argument list as funobj. if scopechain is supplied, it uses scopechain as its enclosing scope. if scopechain is omitted, it creates a new function object in cx's global. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject : choosing a default prototype explains exactly how this is computed. js::clonefunctionobject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer to a javascript function object (see js_objectisfunction). on success, js::clonefunctionobject returns a pointer to the newly created object...
JS::CreateError
tring message, mutablehandlevalue rval); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. type jsexntype the exception's type. stack js::handlestring or js::handleobject the value of error.prototype.stack. filename js::handlestring the value of error.prototype.filename. linenumber uint32_t the value of error.prototype.linenumber. columnnumber uint32_t the value of error.prototype.columnnumber. report jserrorreport * a pointer to jserrorreport instance. message js::handlestring the value of error.prototype.message. ...
JS::ProtoKeyToId
dermonkey 38 convert a jsprotokey to js id. syntax void js::protokeytoid(jscontext *cx, jsprotokey key, js::mutablehandleid idp); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. key jsprotokey the prototype key to convert. vp js::mutablehandleid out parameter. *idp receives the converted id. description js::protokeytoid converts a specified js prototype key key, to a js id. js::protokeytoid stores a jsid to *idp. see also mxr id search for js::protokeytoid js_idtoprotokey bug 987669 ...
JSExnType
(lower bound) jsexn_err error jsexn_internalerr internalerror jsexn_evalerr evalerror jsexn_rangeerr rangeerror jsexn_referenceerr referenceerror jsexn_syntaxerr syntaxerror jsexn_typeerr typeerror jsexn_urierr urierror jsexn_limit (upper bound) description these types are part of a jserrorformatstring structure. they define which error to throw in case of a runtime error. ...
JSNewEnumerateOp
idp js::mutablehandleid obsolete since jsapi 37 in/out parameter. the meaning depends on enum_op. see the description below. description from spidermonkey 38, jsnewenumerateop is the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are called in order. the properties each op adds to the properties vector are added to the set of values the for-in loop will iterate over. all of this is nonstandard. an object is "enumerated" when it's the target of a for-in loop or js_enumerate. all other property inspection, including object.keys(obj), goes through [[ownkeys]]. the callback...
JSObject
jsobject is the type of javascript objects in the jsapi. objects are made up of the following parts: most objects have a prototype. see js_getprototype. an object inherits properties, including methods, from its prototype (which is another object). most objects have a parent. see js_getparent. an object's parent is another object, usually either the global object or an object that represents an activation record. the javascript engine sometimes uses this relationship to implement lexical scoping. security-sensitive applications can use this relationship to make every object a member of some security domain. almost every object can have any number of its own properties. the term own property refers to a property of an object that is not inherited from its prototype. each propert...
JSObjectOps.lookupProperty
d the name or index of the property to look up. objp jsobject ** out parameter. if the property is found, the callback stores the object on which the property was found in *objp. propp jsproperty ** out parameter. on success, the callback stores in *propp a pointer to the property, if it exists, or null if it doesn't. description look for id in obj and its prototype chain, returning js_false on error or exception, js_true on success. on success, return null in *propp if id was not found. if id was found, return the first object searching from obj along its prototype chain in which id names a direct property in *objp, and return a non-null, opaque property pointer in *propp. if jslookuppropop succeeds and returns with *propp non-null, that pointer may be pas...
JSProtoKey
this article covers features introduced in spidermonkey 24 possible standard object prototype types. value prototype in javascript jsproto_null a dummy key for invalid prototype. mxr search for jsproto_null jsproto_object object mxr search for jsproto_object jsproto_function function mxr search for jsproto_function jsproto_array array mxr search for jsproto_array jsproto_boolean boolean mxr search for jsproto_boolean jsproto_json json mxr search for jsproto_json jsproto_date date mxr search for jsproto_date jsproto_math math mxr search for jsproto_math jsproto_number number mxr search for jsproto_number jsproto_strin...
JSResolveOp
the following hook: jsclass.resolve callback is called when a property is not found on an object. it can be used to implement lazy properties. js looks for a property in an object, and if not found, tries to resolve the given id. after calling resolve, the engine looks again to see if resolve defined obj[id]. if so, the property lookup succeeds. if not, the process is repeated with obj's prototype. see also mxr id search for jsresolveop jsclass jsnewresolveop bug 993026 ...
JS_AlreadyHasOwnProperty
design, this search may not find a property that other property lookup functions, such as js_lookupproperty, would find. for native objects—objects whose properties are stored in the default data structure provided by spidermonkey—these functions simply check that data structure to see if the specified field is present. they do not search anywhere else for the property. this means that: the prototype chain of obj is not searched. the object's jsclass.resolve hook is not called, so lazily defined properties are not found. (this is the only api that can directly detect that a lazily resolved property has not yet been resolved.) shared, permanent, delegated properties are not found. (such properties are an implementation detail of spidermonkey. they are meant to be a transparent optimization; ...
JS_CheckAccess
r. on success, *attrsp receives the property attributes. description js_checkaccess determines whether the property of obj given by id can be accessed by the code currently running in the context cx. the mode parameter specifies what kind of access to check for. it is one of the following values: value description jsacc_proto check for permission to read to obj's prototype. (this is redundant with passing the string id "__proto__" as id.) jsacc_parent check for permission to read obj's parent. (this is redundant with passing the string id "__parent__" as id.) jsacc_import check for permission to import the property. jsacc_watch check for permission to place a watchpoint on the property. jsacc_read check for permission...
JS_ClearNonGlobalObject
t in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_clearnonglobalobject removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. to remove a single property from an object, use js_deleteproperty. to remove a single array object element, use js_deleteelement. see also js_deleteproperty js_deleteelement bug 1043281 ...
JS_ClearScope
the context in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_clearscope removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. to remove a single property from an object, use js_deleteproperty. to remove a single array object element, use js_deleteelement. see also js_deleteproperty js_deleteelement js_clearnonglobalobject js_setallnonreservedslotstoundefined bug 749371 ...
JS_CloneFunctionObject
clone. parent jsobject * the new function's parent. description js_clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj, but uses parent as its enclosing scope. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject: choosing a default prototype explains exactly how this is computed. js_clonefunctionobject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer to a javascript function object (see js_objectisfunction). on success, js_clonefunctionobject returns a pointer to the newly created object. if ...
JS_DefineObject
bject. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to which this new object belongs as a property. name const char * name of the property being defined in obj to hold the new object. clasp const jsclass * class to use for the new object. proto js::handleobject prototype object to use for the new object, or null. obsolete since jsapi 38 flags unsigned property attributes for the new property being defined. description js_defineobject creates a new object of the class clasp and assigns it to a new property of an existing object, obj. name is the property name to assign to obj to hold the new object, and flags contains the property attributes...
JS_DeleteElement
bj js::handleobject object from which to delete an element. index uint32_t index number of the element to delete. result js::objectopresult &amp; (out parameter) receives the result of the operation. description js_deleteelement removes a specified element or numeric property, index, from an object, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement returns true. otherwise it returns false. for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the error before returning false. for javascript 1.3 and later, the attempt is...
JS_DeleteElement2
ent. index uint32_t index number of the element to delete. succeeded bool * out parameter. on success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise. description js_deleteelement2 removes a specified element or numeric property, index, from an object, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement2 stores true to *succeeded and returns true. otherwise it returns false and the value of *succeeded is undefined. notes per the ecma standard, js_deleteelement2 removes read-only properties from objects as long as they are not also permanent. for javascri...
JS_DeleteProperty
n object, obj. js_deletepropertybyid is the same but takes a jsid for the property name. these functions are identical to js_deleteproperty2 and js_deletepropertybyid2 except that they do not have an out parameter. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is called. no property is deleted, but this is not an error. if obj has the specified property but it is permanent, nothing happens. no property is deleted, but this is not an error. otherwise obj has a non-permanent own property with the given name or id. in this case, obj's jsclass.delproperty hook is called. if the hook returns false, the error is propaga...
JS_DeleteProperty2
succeeded. it behaves like the javascript expression delete obj[name]. js_deleteucproperty2 is the unicode version of the function. js_deletepropertybyid2 is the same but takes a js::handleid for the property name. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). no property is deleted, but this is not an error. if obj has the specified property but it is permanent, then *succeeded receives false. no property is deleted, but this is not an error. otherwise obj has a non-permanent own property with the given name or id. in this case, *succeeded is ...
JS_Enumerate
uires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object whose properties are to be enumerated. description js_enumerate gets the ids of all own properties of the specified object, obj, that have the jsprop_enumerate attribute. (the term own property refers to a property that is not inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in loop, which converts all property ids to strings and also enumerates inherited properties. this calls obj's jsclass.enumerate hook. on success, js_enumerate returns a pointer to the first element of an array of property ids. the application must free this array using js_destroyidarray. on error or exception, js_enumerate returns null.
JS_GetConstructor
d, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; the object whose constructor is to be returned. description js_getconstructor retrieves the constructor property of a given object, obj. if the result is a function object, js_getconstructor returns a pointer to that object. otherwise, it reports an error and returns null. to get an object's prototype, use js_getprototype. to get an object's parent, use js_getparent. see also mxr id search for js_getconstructor ...
JS_GetElement
in a request on this jscontext. obj js::handleobject the object to search for the element. index uint32_t index of the element to look up. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the element, if it exists, and undefined otherwise. description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_getelement sets *vp to the element's current value. if not, it sets *vp to undefined and returns true (to indicate no error occurred). if the search fails with an error or exception, js_getelement returns false, and the value left in *vp is undefined. see also mxr id search for js_getelement js_defineelement js_d...
JS_GetOwnPropertyDescriptor
::mutablehandle&lt;jspropertydescriptor&gt; out parameter. on success, if no property is found, desc->obj is set to null. if a property is found, *desc receives a description of it. description js_getownpropertydescriptor and js_getownpropertydescriptorbyid get a detailed description of that property (returned in desc->obj). if desc->obj is null, then this property was not found on the prototype chain. see also mxr id search for js_getownpropertydescriptor mxr id search for js_getownpropertydescriptorbyid mxr id search for js_getownucpropertydescriptor js_getpropertydescriptor js_getpropertydescriptorbyid jspropertydescriptor bug 893186 bug 1135731 -- added js_getownpropertydescriptor ...
JS_GetParent
f obj does not have a parent. warning: the result may be an internal-use-only object. such an object should not be passed to any other jsapi function that could expose it to script code. each object is assigned a parent when it is created: the standard library objects and functions all have the global object as their parent. objects created by standard library functions, such as array.prototype.concat, have the global object as their parent. an object created by a script via the new keyword has the same parent as the constructor. for example, after d = new date, d has the same parent as date, ordinarily the global object. an object created by a script via implicit conversion (the ecmascript toobject operator), an object initializer ({a: 1, b: 2}), or an array initializer ([1, 2, 3]),...
JS_GetProperty
e property to look up. namelen size_t (in js_getucproperty only) the length of name, in characters; or -1 to indicate that name is null-terminated. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getproperty examines a specified js object obj and its prototype chain for a property with the specified name. it behaves like the javascript expression obj[name]. js_getucproperty is the unicode version of the function. js_getpropertybyid is the same but takes a js::handleid for the property name. in the simplest case, js_getproperty stores the value of the property in *vp and returns true. however, several different hooks can affect property gets. the full ...
JS_GetPropertyAttributes
ion js_getpropertyattributes retrieves the property attributes of the property with the given name on a given object, obj. js_getucpropertyattributes is the unicode version of the function. if an error occurs, the return value is js_false, and the values left in *attrsp and *foundp are unspecified. if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false. the value left in *attrsp is unspecified. the return value is js_true (to indicate that no error occurred). if the property exists and belongs to obj, then *foundp is set to js_true, *attrsp is set to the logical or of zero or more property attributes flags, and the function returns js_true. see also property attributes bug 893186 ...
JS_GetPropertyDefault
name or id const char * or js::handleid name of the property to look up. def js::handlevalue default value if the property is not found. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getpropertydefault examines a specified js object obj and its prototype chain for a property with the specified name. on success, these functions set *vp to the current value of the property, or def if obj has no such property, and return true. on an error or exception, these functions return false, and the value left in *vp is undefined. see also bug 905774 ...
JS_GetPropertyDescriptor
the property to look up. desc js::mutablehandle&lt;jspropertydescriptor&gt; out parameter. on success, if no property is found, desc->obj is set to null. if a property is found, *desc receives a description of it. description js_getpropertydescriptor and js_getpropertydescriptorbyid find a specified property of an object and gets a detailed description of that property on the prototype chain (returned in desc->obj). if desc->obj is null, then this property was not found on the prototype chain. see also mxr id search for js_getpropertydescriptor mxr id search for js_getpropertydescriptorbyid js_getownpropertydescriptor js_getownpropertydescriptorbyid jspropertydescriptor bug 482381 - added js_getpropertydescriptorbyid bug 893186 - added js_getpropertydescriptor ...
JS_HasElement
quest. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to search for the element. index uint32_t index of the element to look up. foundp bool * out parameter. on success, it stores true to *foundp, false otherwise. description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_haselement sets *foundp to true. if not, it sets *foundp to false and returns true (to indicate no error occurred). if the search fails with an error or exception, js_haselement returns false, and the value left in *foundp is undefined. see also mxr id search for js_haselement js_defineelement js_deleteelem...
JS_HasProperty
up. namelen size_t (only in js_hasucproperty) the length of name in characters, or -1 to indicate that name is null-terminated. foundp bool * non-null pointer to a variable of type bool. on success, js_hasproperty stores true in this variable if obj has a property with the given name, and false if not. description js_hasproperty searches an object, obj, and its prototype chain, for a property with the specified name. it behaves like the javascript expression name in obj. js_hasucproperty is the corresponding unicode api. js_haspropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and returns true. if the object obj has no such property, the function sets *foundp to false and returns tru...
JS_IdToProtoKey
ontext *cx, js::handleid id); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. id js::handleid the property identifier to convert. description js_idtoprotokey converts a specified js id, id, to a prototype key. on success, js_idtoprotokey returns a jsprotokey. otherwise it returns jsproto_null. see also mxr id search for js_idtoprotokey js::protokeytoid bug 933681 ...
JS_InstanceOf
uments provided by the engine for args with js::callargsfromvp(argc, vp). when args is non-null, js_instanceof behaves as follows. if obj is of the given class, it returns true. otherwise, it returns false; it also reports a typeerror containing the function's name. note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain. js_hasinstance is similar to instanceof. see also mxr id search for js_instanceof js_hasinstance js_getclass bug 959787 ...
JS_NewGlobalObject
hookoption js::onnewglobalhookoption see debugger api hook added in spidermonkey 31 options const js::compartmentoptions &amp; the option for new compartment (passed to jscompartment constructor). added in spidermonkey 31 description js_newglobalobject creates a new global object based on the specified class. the new object has no parent. it initially has no prototype either, since it is typically the first object created; call js_initstandardclasses to create all the standard objects, including object.prototype, and set the global object's prototype. the constructor clasp-&gt;construct is not called. on success, js_newglobalobject returns a pointer to the new object. otherwise it returns null. debugger api hook during global creation, we fire notification...
JS_NewPlainObject
eates a new plain javascript object. syntax jsobject * js_newplainobject(jscontext *cx); name type description cx jscontext * the context in which to create the new object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]]. on success, js_newplainobject returns a pointer to the new object. otherwise it returns nullptr. see also mxr id search for js_newplainobject js_newobject bug 1125356 ...
JS_NewPropertyIterator
this jscontext. obj js::handle&lt;jsobject*&gt; the object whose properties are to be enumerated. description create an object to iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this returns an iterator object that can be passed to js_nextproperty to fetch the property ids. on error, it returns null. the iterator object created by this function is not a javascript iterator. it is an opaque object with no properties visible from javascript. see also bug 1081660 ...
JS_NewScriptObject
object. as long as the script object is reachable, the jsscript and its components are protected from garbage collection; when the script object is collected, the jsscript and its contents are freed. once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope). a script object has no properties, and its prototype is object.prototype. so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it. on success, js_newscriptobject returns a pointer to the script's object. otherwise it returns null. (the name "js_newscriptobject" suggests that the script object is freshly allocated; this was the case in older versions of the api, but now the script obje...
JS_ResolveStandardClass
id an id of a standard class name, which must contain either a string or an int. resolved bool * out parameter. if the id is resolved, true is stored into *resolved if success. false otherwise. description js_resolvestandardclass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing true in *resolved. if id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just return true. return false on error, as usual for bool result-typed api entry points. this api can be called directly from a global object class's resolve op, to define standard classes lazily. the class's enumerate op should call ...
JS_SetAllNonReservedSlotsToUndefined
ect. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_setallnonreservedslotstoundefined assignes undefined to all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. see also mxr id search for js_setallnonreservedslotstoundefined bug 749371 ...
Property attributes
ails. mxr id search for jsprop_setter jsprop_shared the property is shared. this is usually the right thing for properties that have getters or setters. this has three effects: the javascript engine does not set aside any memory for the property's value. the value is determined entirely by the getter. (the property has no stored value.) assignment via the prototype chain is affected. assigning to obj.x, where obj inherits a non-shared property from its prototype, creates a new own data property on obj; the prototype's .x is not shared with its children. if the inherited property is shared, the setter is called instead. if the property is also jsprop_permanent, then certain aspects of inheriting the property via the prototype chain are affected. do not ...
Parser API
instance of syntaxerror is thrown. the syntax error object thrown by reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). the linenumber and filename properties of the syntax error object indicate the source location of the syntax error. node objects by default, reflect.parse() produces node objects, which are plain javascript objects (i.e., their prototype derives from the standard object prototype). all node types implement the following interface: interface node { type: string; loc: sourcelocation | null; } the type field is a string representing the ast variant type. each subtype of node is documented below with the specific string of its type field. you can use this field to determine which interface a node implements. the loc field...
SpiderMonkey 1.8.8
ly use js_new instead, or use this reimplementation as a short-term fix) js_newcompartmentandglobalobject (use js_newglobalobject instead.) jspd_argument jsval_is_object() (use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null). js_isscriptframe jsclass_new_resolve_gets_start flag js_newnumbervalue api changes break out and discuss all api changes here... jsclass prototype has changed a number of optional members have been removed from the jsclass prototype. jsclass callback changes many of the jsclass callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc. atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to js...
SpiderMonkey 17
andglobalobject (use js_newglobalobject instead.) jspd_argument jsval_is_object() (use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null). js_isscriptframe jsclass_new_resolve_gets_start flag js_newnumbervalue js_finalizestub js_clearnewbornroots jsclass_mark_is_trace flag js_setscriptstackquota api changes break out and discuss all api changes here... jsclass prototype has changed a number of optional members have been removed from the jsclass prototype. jsclass callback changes many of the jsclass callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc. atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to js...
Feed content access API
his case, we're loading a document into a string, then parsing that string using its parsefromstring() method. however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a method called handleresult() on the feedtestresultlistener object. ...
Generic factory
tablishes the generic factory's constructor function, which will be called * by createinstance. */ ns_imethod setconstructor(constructorprocptr constructor) = 0; }; using nsigenericfactory is simple. create a new instance from the repository with a cid of ns_genericfactory_cid, and and iid of ns_igenericfactory_iid. define a constructor function that matches the constructorprocptr prototype, and call nsigenericfactory::setconstructor with a pointer to that function. you're done. you now have a fully functional factory object. examples class nsicomponent : public nsisupports { public: ns_imethod dosomething() = 0; }; class mycomponent : public nsicomponent { public: mycomponent(); virtual ~mycomponent(); static ns_method create(nsisupports *aouter, refnsiid aiid, void **a...
Index
Mozilla › Tech › XPCOM › Index
arange function copies data into a section of the string's internal buffer. this is a low-level api. 1254 ns_utf16tocstring xpcom, xpcom api reference the ns_utf16tocstring function converts the value of a nsastring instance from utf-16 to the specified multi-byte encoding and stores the result in a nsacstring instance. 1255 nsgetmoduleproc this function prototype provides the xpcom entry-point into a module. 1256 nsiabcard/thunderbird3 interfaces, interfaces:scriptable, xpcom, xpcom api reference, thunderbird the nsiabcard interface is used to represent and manipulate cards in the address book. in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it ...
Components.results
be enumerated using a for-in loop. usage implementing nsisupports the standard nsisupports is usually implemented in javascript by using components.results to get a failure return value if does not implement the given interface. note the common use of an abbreviation for components.results, cr: const ci = components.interfaces, cr = components.results; function class() { /* ... */ } class.prototype = { /* ... */ queryinterface: function(id) { if (id.equals(ci.imyinterface)) return this; throw cr.ns_error_no_interface; } }; ...
Components.utils
getcomponentsforscope() this seemingly-paradoxical api allows privileged code to explicitly give unprivileged code a reference to its own components object (whereas it's normally hidden away on a scope chain visible only to xbl methods). see also specialpowers.getcomponents. getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example). getjstestingfunctions() getobjectprincipal() gets the nsiprincipal for the given javascript object. getweakreference() gets a weak reference for the object passed in. import() loads a js module into the current script, without sharing a scope. importglobalproperties() specify a list of constructors to im...
Components.utils.waiveXrays
to see an expando property on a dom object. in these cases you can use waivexrays to remove xray vision for the object. waiving xrays is transitive, so waiving it for an object automatically waives it for any properties of that object (and their properties, and so on). if you waive xray vision, you can no longer trust that any of the object's properties are what you expect: any of them, including prototypes and accessors, could have been redefined by the less-privileged code. to undo waivexrays and get xray vision back, call components.utils.unwaivexrays on the object. the result of waivexrays is just like the wrappedjsobject property for xrayed objects, but it's more useful because you can call it on primitives or objects that aren't xrays, in which case it just returns the argument you passed in.
Components object
he scope of the specified object's compartment. may only be called from javascript code. utils.evalinsandbox runs javascript code in a sandbox, usually used to run code with restricted privileges. utils.forcegc forces a garbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a weak reference for the object passed in. utils.import loads a javascript module into the current script, without sharing a scope. utils.lookupmethod looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. ...
nsIObserver
hin observe. example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic. see observer notifications for a list of built-in topics possible. observing preferences works slightly differently. see code snippets:preferences - using preference observers for an example. function myobserver() { this.register(); } myobserver.prototype = { observe: function(subject, topic, data) { // do your stuff here. }, register: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(this, "mytopicid", false); }, unregister: function() { var observerservice = components.clas...
nsIPropertyBag
services.appinfo.os simply tells us winnt only, this is not helpful to differentiate between windows xp, vista, 7, etc. to do this use nsipropertybag: services.sysinfo.getproperty("version"); //output 5.1 services.sysinfo.getproperty("name"); //output windows_nt services.sysinfo.getproperty("arch"); //output x86 services.sysinfo.getprope...
nsIRunnable
*/ interface nsirunnable : nsisupports { /** * the function implementing the task to be run. ...
nsIScriptError
if you want to log an error at chrome level you should set a category from the first section (leaving it empty might log it as content error). as addon author i would recommend using "chrome javascript" for logging exceptions caused by addon code. ...
nsITraceableChannel
rce this.responsebody; // we'll set this to the this.responsestatuscode; this.deferreddone = { promise: null, resolve: null, reject: null }; this.deferreddone.promise = new promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject; }.bind(this.deferreddone)); object.freeze(this.deferreddone); this.promisedone = this.deferreddone.promise; } tracinglistener.prototype = { ondataavailable: function(arequest, acontext, ainputstream, aoffset, acount) { var istream = new binaryinputstream(ainputstream) // binaryainputstream var sstream = new storagestream(8192, acount, null); // storagestream // not sure why its 8192 but thats how eveyrone is doing it, we should ask why var ostream = new binaryoutputstream(sstream.getoutputstream(0)); // binaryoutputstream ...
nsGetModuleProc
#include "nsxpcom.h" typedef nsresult (pr_callback *nsgetmoduleproc)( nsicomponentmanager *acompmgr, nsifile* alocation, nsimodule** aresult ); parameters acompmgr [in] the xpcom component manager. alocation [in] the location of the module if any. may be null. aresult [out] the nsimodule instance. ...
XPCOM reference
7201ns_addrefmacrons_assertionmacrons_ensure_arg_pointermacrons_errorthrows a assertion (ns_assertion) with the text "error: (error text)", so writes this text to console (stderr) and to debug logs (nspr logging). this macro is meant for critical errors; like assertions, ns_errors should not be reachable.ns_if_addrefmacrons_if_releasemacrons_releasemacrons_warningmacronsgetmoduleprocthis function prototype provides the xpcom entry-point into a module.nsiabcard/thunderbird3the nsiabcard interface is used to represent and manipulate cards in the address book. in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible.nsicookie2 mozilla 1 8 branchnsimsgsearchvaluedefined in comm-central/ mailnews/ ba...
Setting HTTP request headers
ttps://developer.mozilla.org/en/xpcom/xpcom_changes_in_gecko_2.0#javascript_components. ...
Adding items to the Folder Pane
ributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberrow(anumber) { this._number = anumber; } numberrow.prototype = { get id() { return "numbers-child-row-" + this._number; }, get text() { return this._number; }, level: 1, open: false, children: [], getproperties: function gne_kid_getprops() {}, // no-op command: function gne_kid_command() { // just going to alert,...
Using JS in Mozilla code
js language features that are implemented in the mozilla js engine are ordinarily safe to use in mozilla code. however, there are a few exceptions, listed here. js language features proper tail calls are not implemented. js standard library features feature standard can be used in code new proxy(target, handler) es2015 yes, but getprototypeof and setprototypeof handlers are not yet implemented. arraybuffer.transfer() proposed for es2016 no, nightly-only for now sharedarraybuffer, sharedint8array..., atomics proposed for es2016 no, nightly-only for now typedobject proposed for es2016 no, nightly-only for now simd proposed for es2016 no, nightly-only for now ...
Working with ArrayBuffers
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 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...
DevTools API - Firefox Developer Tools
on object, do // build: (window, target) => new mypanel(window, target), function mypanel(window, target) { // the window object that has loaded the url defined in the tooldefinition this.window = window; // the target this toolbox is debugging. this.target = target; // do synchronous initialization here. window.document.body.addeventlistener("click", this.handleclick); } mypanel.prototype = { open: function() { // any asynchronous operations should be done here. return this.dosomethingasynchronous() .then(() => this); }, destroy: function() { // synchronous destruction. this.window.document.body.removeeventlistener("click", this.handleclick); // async destruction. return this.destroysomethingasynchronosly() .then(() => console.log("destr...
Dominators view - Firefox Developer Tools
n object, and so on. if you look in the dominators tree panel, you can trace the same path there. if either of these references were removed, the items below them could be garbage-collected. each connection in the graph is labeled with the variable name for the referenced object. sometimes there's more than one retaining path back from a node: here there are three paths back from the documentprototype node to a gc root. if one were removed, then the documentprototype would still not be garbage-collected, because it's still retained by the other two path. example let's see how some simple code is reflected in the dominators view. we'll use the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name. taking a snapsh...
Rich output - Firefox Developer Tools
...
CSSStyleSheet.insertRule() - Web APIs
working draft no change from document object model (dom) level 2 style specification. document object model (dom) level 2 style specificationthe definition of 'cssstylesheet.insertrule' in that specification. obsolet...
CSSUnparsedValue.entries() - Web APIs
syntax cssunparsedvalue.entries(obj) parameters obj the cssunparsedvalue whose enumerable own property [key, value] pairs are to be returned. ...
CSSUnparsedValue - Web APIs
parsedvalue() creates a new cssunparsedvalue object. properties cssunparsedvalue.length returns the number of items in the cssunparsedvalue object. methods cssunparsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object. cssunparsedvalue.keys() returns a new array iterator object that contains the keys for each index in the cssunparsedvalue object. cssunparsedvalue.values() returns a new array iterator object that contains the values for each index in the cssunparsedvalue object. s...
Using the CSS Typed Object Model - Web APIs
tton 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 the image — this is returned even if the original url() value was relative. had the background image been a gradient or multiple background images, .get('background-image') would have returned a cssstylevalue. the cssimage...
CSS Typed Object Model API - Web APIs
cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties. cssunparsedvalue.entries() method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() method executing a provided function once for each element of the cssunparsedvalue. cssunparsedvalue.keys() method returning a new array iterator object that contains the keys for each index in the array. csskeywordvalue serialization the csskeywordvalue interface of the the css typed object model api creates an object to represent css keywords an...
ChildNode.replaceWith() - Web APIs
} else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode === arguments[0]) parent.replacechild(currentnode, this); else // if currentnode isn't the first parent.insertbefore(currentnode, this.nextsibling); } } if (!element.prototype.replacewith) element.prototype.replacewith = replacewithpolyfill; if (!characterdata.prototype.replacewith) characterdata.prototype.replacewith = replacewithpolyfill; if (!documenttype.prototype.replacewith) documenttype.prototype.replacewith = replacewithpolyfill; specification specification status comment domthe definition of 'childnode.replacewith()' in th...
DOMParser - Web APIs
Web › API › DOMParser
text/html") // returns an htmldocument, which also is a document. domparser html extension /* * domparser html extension * 2012-09-04 * * by eli grey, http://eligrey.com * public domain. * no warranty expressed or implied. use at your own risk. ...
DOMTokenList.replace() - Web APIs
ole.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class. the following code will only work with ie10-11. to use with earlier versions of ie, refer to the polyfill at element.classlist#polyfill domtokenlist.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } specifications specification status comment domthe definition of 'replace()' in that specification. living standard initial definition ...
Document.getElementsByClassName() - Web APIs
red' and 'test' classes: document.getelementsbyclassname('red test') get all elements that have a class of 'test', inside of an element that has the id of 'main': document.getelementbyid('main').getelementsbyclassname('test') get the first element with a class of 'test', or undefined if there is no matching element: document.getelementsbyclassname('test')[0] we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value. here we'll find all div elements that have a class of 'test': var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement){ return testelement.nodename === 'div'; }); get the first element whose class is 'test' this is the most commonly...
Document.registerElement() - Web APIs
nstructor for the new element. note: this is an experimental technology. the browser you use it in must support web components. see enabling web components in firefox. syntax var constructor = document.registerelement(tag-name, options); parameters tag-name the name of the custom element. the name must contain a dash (-), for example my-tag. optionsoptional an object with properties prototype to base the custom element on, and extends, an existing tag to extend. both of these are optional. example here is a very simple example: var mytag = document.registerelement('my-tag'); now the new tag is registered in the browser. the mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendchild(new mytag()); this i...
DocumentTimeline.DocumentTimeline() - Web APIs
t moment of the active document for the current browsing context. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
Element.currentStyle - Web APIs
it returns the units set in css while window.getcomputedstyle() returns the values in pixels. polyfill this polyfill returns the values in pixels and is likely to be rather slow, as it has to call window.getcomputedstyle() every time its value is read. /* any copyright is dedicated to the public domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ if (!("currentstyle" in element.prototype)) { object.defineproperty(element.prototype, "currentstyle", { get: function() { return window.getcomputedstyle(this); } }); } specification not part of any specification. microsoft had a description on msdn. 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...
Element.hasAttributes() - Web APIs
the hasattributes() method of the element interface returns a boolean indicating whether the current element has any attributes or not. syntax var result = element.hasattributes(); return value result holds the return value true or false. examples let foo = document.getelementbyid('foo'); if (foo.hasattributes()) { // do something with 'foo.attributes' } polyfill ;(function(prototype) { prototype.hasattributes = prototype.hasattributes || function() { return (this.attributes.length > 0); } })(element.prototype); specifications specification status comment domthe definition of 'element.hasattributes()' in that specification. living standard moved from the node interface to the more specialized element interface. document object mo...
Element.toggleAttribute() - Web APIs
odes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - polyfill if (!element.prototype.toggleattribute) { element.prototype.toggleattribute = function(name, force) { if(force !== void 0) force = !!force if (this.hasattribute(name)) { if (force) return true; this.removeattribute(name); return false; } if (force === false) return false; this.setattribute(name, ""); return true; }; } specification specification status ...
Recommended Drag Types - Web APIs
url); currentevent.datatransfer.setdata("application/x-moz-file-promise-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-dest-filename", leafname); currentevent.datatransfer.mozsetdataat('application/x-moz-file-promise', new dataprovider(success,error), 0, components.interfaces.nsisupports); function dataprovider(){} dataprovider.prototype = { queryinterface : function(iid) { if (iid.equals(components.interfaces.nsiflavordataprovider) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, getflavordata : function(atransferable, aflavor, adata, adatalen) { if (aflavor == 'application/x-moz-file-promise') { var urlprimitive = {}; ...
KeyboardEvent.isComposing - Web APIs
n value indicating if the event is fired within a composition session, i.e. after compositionstart and before compositionend. syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // return false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'keyboardevent.prototype.iscomposing' in that specification. obsolete initial definition. ...
KeyboardLayoutMap.entries - Web APIs
the entries read-only property of the keyboardlayoutmap interface returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). syntax keyboardlayoutmap.entries() value an array of the given keyboardlayoutmap object's own enumerable property [key, value] pairs. specifications specification status comment keyboard mapthe definition of 'entries' in that specification. editor's draft initial definition. ...
KeyboardLayoutMap - Web APIs
the string associated with specific physical keys. a list of valid keys is found in the ui events keyboardevent code values specification. properties keyboardlayoutmap.entries read only returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). keyboardlayoutmap.keys read only returns a new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only returns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only returns a new array iterator object that contains the values for each index in the keyboardlayoutmap object. met...
MSSiteModeEvent - Web APIs
element that is the target of the event. timestamp gets the time, in milliseconds, when an event occurred. ...
Node.isConnected - Web APIs
Web › API › Node › isConnected
the shadow dom shadow.appendchild(style); console.log(style.isconnected); // returns true polyfill node.isconnected can be polyfilled with the following code for ie10 and edgehtml: /* * node.isconnected polyfill for ie and edgehtml * 2020-02-04 * * by eli grey, https://eligrey.com * public domain. * no warranty expressed or implied. use at your own risk. */ if (!('isconnected' in node.prototype)) { object.defineproperty(node.prototype, 'isconnected', { get() { return ( !this.ownerdocument || !( this.ownerdocument.comparedocumentposition(this) & this.document_position_disconnected ) ); }, }); } specifications specification status comment domthe definition of 'isconnected' in that specification. ...
Notification - Web APIs
tion.onshow a handler for the show event. it is triggered when the notification is displayed. methods static methods these methods are available only on the notification object itself. notification.requestpermission() requests permission from the user to display notifications. instance methods these properties are available only on an instance of the notification object or through its prototype. the notification object also inherits from the eventtarget interface. notification.close() programmatically closes a notification instance. examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifi...
OVR_multiview2 - Web APIs
on exposes 4 constants that can be used in getparameter() or getframebufferattachmentparameter(). framebuffer_attachment_texture_num_views_ovr number of views of the framebuffer object attachment. framebuffer_attachment_texture_base_view_index_ovr base view index of the framebuffer object attachment. max_views_ovr the maximum number of views. most vr headsets have two views, but there are prototypes of headset with ultra-wide fov using 4 views which is currently the maximum number of views supported by multiview. framebuffer_incomplete_view_targets_ovr if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete. calling checkframebufferstatus for a framebuffer in this sta...
ParentNode.append() - Web APIs
Web › API › ParentNode › append
he following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? argitem : document.createtextnode(string(argitem))); }); this.appendchild(docfrag); } }); }); })([element.prototype, document.prototype, documentfragment.protot...
StylePropertyMapReadOnly.entries() - Web APIs
syntax stylepropertymapreadonly.entries() parameters none. ...
StylePropertyMapReadOnly - Web APIs
map(). properties stylepropertymapreadonly.size returns an unsinged long integer containing the size of the stylepropertymapreadonly object. methods stylepropertymapreadonly.entries() returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly. stylepropertymapreadonly.get() returns the value of the specified property. stylepropertymapreadonly.getall() returns an array of cssstylevalue objects containing the values for the provided property. stylepropertymapreadonly.has() indicates whether the specif...
Migrating from webkitAudioContext - Web APIs
// when starting the source, put it at the end of the array, // and set a handler to make sure it gets removed when the // audiobuffersourcenode reaches its end. // first argument is the audiobuffersourcenode to start, other arguments are // the argument to the |start()| method of the audiobuffersourcenode. function startsource() { var src = arguments[0]; var startargs = array.prototype.slice.call(arguments, 1); src.onended = function() { sources.splice(sources.indexof(src), 1); } sources.push(src); src.start.apply(src, startargs); } function activesources() { return sources.length; } var src0 = context.createbuffersource(); var src0 = context.createbuffersource(); // set buffers and other parameters... startsource(src0, 0); startsource(...
The structured clone algorithm - Web APIs
likewise throws a data_clone_err exception. certain object properties are not preserved: the lastindex property of regexp objects is not preserved. property descriptors, setters, getters, and similar metadata-like features are not duplicated. for example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default. the prototype chain is not walked or duplicated. note: native error types can be cloned in chrome, and firefox is working on it. supported types object type notes all primitive types however, not symbols. boolean objects string objects date regexp lastindex is not preserved. blob file fi...
Window - Web APIs
Web › API › Window
icrange() constructor which creates a staticrange object. worker used for creating a web worker. xmlserializer converts a dom tree into xml or html source. properties this interface inherits properties from the eventtarget interface and implements properties from the windoworworkerglobalscope and windoweventhandlers mixins. note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below. window.closed read only this property indicates whether the current window is closed or not. window.console read only returns a reference to the console object which provides access to the browser's debugging console. window.controllers read only returns the xul controller objects for the current chrome window. window.cus...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
nction); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. return value undefined. ...
WorkerGlobalScope.self - Web APIs
g like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null caller: null isarray: function isarray() { [native code] } length: 1 name: "array" observe: function observe() { [native code] } prototype: array[0] unobserve: function unobserve() { [native code] } __proto__: function empty() {} <function scope> arraybuffer: function arraybuffer() { [native code] } blob: function blob() { [native code] } boolean: function boolean() { [native code] } dataview: function dataview() { [native code] } date: function date() { [native code] } dedicatedworkerglobal...
:scope - CSS: Cascading Style Sheets
Web › CSS › :scope
resting paragraph. sorry about that. </p> <p id="output"></p> result direct children a situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved element. ...
DOM onevent handlers - Developer guides
ication. living standard html5the definition of 'event handlers' in that specification. recommendation browser compatibility detecting the presence of event handler properties you can detect the presence of an event handler property with the javascript in operator. for example: if ("onsomenewfeature" in window) { /* do something amazing */ } event handlers and prototypes you can't set or access the values of any idl-defined attributes on dom prototype objects. that means you can't, for example, change window.prototype.onload. in the past, event handlers (onload, etc.) weren't implemented as idl attributes in gecko, so you were able to do this for those. now you can't. this improves compatibility. ...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
c = url.createobjecturl(file); listitem.appendchild(image); listitem.appendchild(para); } else { para.textcontent = `file name ${file.name}: not a valid file type. update your selection.`; listitem.appendchild(para); } list.appendchild(listitem); } } } the custom validfiletype() function takes a file object as a parameter, then uses array.prototype.includes() to check if any value in the filetypes matches the file's type property. if a match is found, the function returns true. if no match is found, it returns false. // https://developer.mozilla.org/docs/web/media/formats/image_types const filetypes = [ "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/...
JavaScript data types and data structures - JavaScript
functions are regular objects with the additional capability of being callable. dates when representing dates, the best choice is to use the built-in date utility in javascript. indexed collections: arrays and typed arrays arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the length property. additionally, arrays inherit from array.prototype, which provides to them a handful of convenient methods to manipulate arrays. for example, indexof (searching a value in the array) or push (adding an element to the array), and so on. this makes arrays a perfect candidate to represent lists or sets. typed arrays are new to javascript with ecmascript 2015, and present an array-like view of an underlying binary data buffer. the following table he...
Control flow and error handling - JavaScript
n 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 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...ca...
Grammar and types - JavaScript
...
Numbers and dates - JavaScript
finite() determines whether the passed value is a finite number. number.isinteger() determines whether the passed value is an integer. number.isnan() determines whether the passed value is nan. more robust version of the original global isnan(). number.issafeinteger() determines whether the provided value is a number that is a safe integer. the number prototype provides methods for retrieving information from number objects in various formats. the following table summarizes the methods of number.prototype. methods of number.prototype method description toexponential() returns a string representing the number in exponential notation. tofixed() returns a string representing the number in fixed-point notation. ...
Unicode property escapes - JavaScript
l properties which are either binary ("boolean-like") or non-binary. for instance, unicode property escapes can be used to match emojis, punctuations, letters (even letters from specific languages or scripts), etc. note: for unicode property escapes to work, a regular expression must use the u flag which indicates a string must be considered as a series of unicode code points. see also regexp.prototype.unicode. note: some unicode properties encompasses much more characters than some character classes (such as \w which matches only latin letters, a to z) but the latter is better supported among browsers (as of january 2020). syntax the following section is also duplicated on this cheatsheet. do not forget to edit it as well, thanks! // non-binary values \p{unicodepropertyvalue} \p{unicode...
JavaScript Guide - JavaScript
math object date object text formatting string literals string object template literals internationalization regular expressions indexed collections arrays typed arrays keyed collections map weakmap set weakset working with objects objects and properties creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importing default exports renaming features aggregating modules...
JavaScript technologies overview - JavaScript
keywords, control flow, object literal initialization, ...) error handling mechanisms (throw, try...catch, ability to create user-defined error types) types (boolean, number, string, function, object, ...) the global object. in a browser, this global object is the window object, but ecmascript only defines the apis not specific to browsers, e.g. parseint, parsefloat, decodeuri, encodeuri... a prototype-based inheritance mechanism built-in objects and functions (json, math, array.prototype methods, object introspection methods, etc.) strict mode browser support as of october 2016, the current versions of the major web browsers implement ecmascript 5.1 and ecmascript 2015, but older versions (still in use) implement ecmascript 5 only. future the major 6th edition of ecmascript was official...
Memory Management - JavaScript
anding the main garbage collection algorithms and their respective limitations. references the main concept that garbage collection algorithms rely on is the concept of reference. within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly). for instance, a javascript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference). in this context, the notion of an "object" is extended to something broader than regular javascript objects and also contain function scopes (or the global lexical scope). reference-counting garbage collection this is the most naive garbage collection algorithm. this algorithm reduces the problem from determining whether o...
extends - JavaScript
her class. 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 class childclass extends parentclass { ... } description the extends keyword can be used to subclass custom classes as well as built-in objects. the .prototype of the extension must be an object or null. examples using extends the first example creates a class called square from a class called polygon. this example is extracted from this live demo (source). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length...
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 repre...
ReferenceError: "x" is not defined - JavaScript
nt script or scope. note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of execution. variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function function numbers() { var num1 = 2, num2 = 3; return num1 + num2; } conso...
ReferenceError: reference to undefined property "x" - JavaScript
mples invalid cases in this case, the property bar is an undefined property, so a referenceerror will occur. ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
ly be used to check if a property is in an object. you can't search in strings, or in numbers, or other primitive types. examples searching in strings unlike in other programming languages (e.g. python), you can't search in strings using the in operator. "hello" in "hello world"; // typeerror: cannot use 'in' operator to search for 'hello' in 'hello world' instead you will need to use string.prototype.indexof(), for example. "hello world".indexof("hello") !== -1; // true the operand can't be null or undefined make sure the object you are inspecting isn't actually null or undefined. var foo = null; "bar" in foo; // typeerror: cannot use 'in' operator to search for 'bar' in 'foo' (chrome) // typeerror: right-hand side of 'in' should be an object, got null (firefox) the in operator always e...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
the javascript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable. message typeerror: invalid 'instanceof' operand "x" (firefox) typeerror: "x" is not a function (firefox) typeerror: right-hand side of 'instanceof' is not an object (chrome) typeerror: right-hand side of 'instanceof' is not callable (chrome) error type typeerror what went wrong? the instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. examples instanceof vs typeof "test" instanceof ""; // typeerror: invalid 'instanceof' operand "" 42 instanceof 0; // typeerror: invalid ...
Arrow function expressions - JavaScript
typeof this.a, this); // undefined 'undefined' window {...} (or the global object) return this.a + 10; // represents global object 'window', therefore 'this.a' returns 'undefined' } }); use of the new operator arrow functions cannot be used as constructors and will throw an error when used with new. var foo = () => {}; var foo = new foo(); // typeerror: foo is not a constructor use of prototype property arrow functions do not have a prototype property. var foo = () => {}; console.log(foo.prototype); // undefined use of the yield keyword the yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). as a consequence, arrow functions cannot be used as generators. function body arrow functions can have either a "conci...
arguments[@@iterator]() - JavaScript
syntax arguments[symbol.iterator]() examples iteration using for...of loop function f() { // your browser must support for..of loop // and let-scoped variables in for loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification. ...
Rest parameters - JavaScript
or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property). ...
AggregateError - JavaScript
the aggregateerror object represents an error when several errors need to be wrapped in a single error. it is thrown when multiple errors need to be reported by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregateerror() creates a new aggregateerror object. instance properties aggregateerror.prototype.message error message, defaults to "". aggregateerror.prototype.name error name, defaults to aggregateerror. examples catching an aggregateerror promise.any([ promise.reject(new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); // true console.log(e.message); // "all promises rejected" console.log(e.name); // "aggregateerror" console.log(e.errors); ...
Array.of() - JavaScript
ts used to create the array. return value a new array instance. description this function is part of the ecmascript 2015 standard. for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. ...
ArrayBuffer - JavaScript
m a local file. constructor arraybuffer() creates a new arraybuffer object. static properties get arraybuffer[@@species] the constructor function that is used to create derived objects. static methods arraybuffer.isview(arg) returns true if arg is one of the arraybuffer views, such as typed array objects or a dataview. returns false otherwise. instance properties arraybuffer.prototype.bytelength the read-only size, in bytes, of the arraybuffer. this is established when the array is constructed and cannot be changed. instance methods arraybuffer.prototype.slice() returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin (inclusive) up to end (exclusive). if either begin or end is negative, it refers to an index from the end of the array, ...
Boolean - JavaScript
g); // 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);...
FinalizationRegistry - JavaScript
.. registry.unregister(theobject); it doesn't have to be the same object, though; it can be a different one: registry.register(theobject, "some value", tokenobject); // ...some time later, if you don't care about `theobject` anymore... registry.unregister(tokenobject); constructor finalizationregistry() creates a new finalizationregistry object. instance methods finalizationregistry.prototype.register() registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected. finalizationregistry.prototype.unregister() unregisters an object from the registry. avoid where possible correct use of finalizationregistry takes careful thought, and it's best avoided if possible. it's also important to avoid relying on any specific behaviors not g...
Function.length - JavaScript
ne with a default value. by contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function. data property of the function constructor the function constructor is itself a function object. its length data property has a value of 1. the property attributes are: writable: false, enumerable: false, configurable: true. property of the function prototype object the length property of the function prototype object has a value of 0. examples using function length console.log(function.length); /* 1 */ console.log((function() {}).length); /* 0 */ console.log((function(a) {}).length); /* 1 */ console.log((function(a, b) {}).length); /* 2 etc. */ console.log((function(...args) {}).length); // 0, rest parameter is not counted cons...
Generator - JavaScript
the generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol. constructor this object cannot be instantiated directly. instead, a generator instance can be returned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() returns a value yielded by the yield expression. generator.prototype.return() returns the given value and finishes the generator. generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). examples an infinite iterator function* infinite() { let index = 0; while (true) { yield index++; } }...
Intl.DisplayNames - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.displaynames() creates a new intl.displaynames object. static methods intl.displaynames.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and returns a string based on the locale and options provided when instantiating intl.displaynames. intl.displaynames.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples region code display names to create an intl.displaynames for a locale and ge...
Intl.ListFormat - JavaScript
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.listformat() creates a new listformat object. static methods intl.listformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.listformat.prototype.format() returns a language-specific formatted string representing the elements of the list. intl.listformat.prototype.formattoparts() returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. examples using format the following example shows how to create a list formatter using the english language. const list...
Intl.PluralRules.select() - JavaScript
syntax pluralcategory = pluralrule.select(number) parameters number the number to get a plural rule for. return value a string representing the pluralization category of the number, can be one of zero, one, two, few, many or other. description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. ...
Intl.PluralRules - JavaScript
bject enables plural-sensitive formatting and plural-related language rules. constructor intl.pluralrules.pluralrules() creates a new intl.pluralrules object. static methods intl.pluralrules.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.pluralrules.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. intl.pluralrules.prototype.select() returns a string indicating which plural rule to use for locale-aware formatting. examples using locales this example shows some of the variations in localized plural rules. in order to get the format of the lan...
JSON.parse() - JavaScript
alid json text. var j; function walk(holder, key) { // the walk method is used to recursively walk the resulting structure so // that modifications can be made. ...
Math.max() - JavaScript
the result is nan. examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); // -10 math.max(-10, 20); // 20 getting the maximum element of an array array.reduce() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return math.max(a, b); }); the following function uses function.prototype.apply() to get the maximum of an array. getmaxofarray([1, 2, 3]) is equivalent to math.max(1, 2, 3), but you can use getmaxofarray() on programmatically constructed arrays. this should only be used for arrays with relatively few elements. function getmaxofarray(numarray) { return math.max.apply(null, numarray); } the new spread operator is a shorter way of writing the apply solution to get th...
Object.defineProperties() - JavaScript
return typeof v === 'function'; } if (typeof desc !== 'object' || desc === null) throw new typeerror('bad desc'); var d = {}; if (hasproperty(desc, 'enumerable')) d.enumerable = !!desc.enumerable; if (hasproperty...
Object.entries() - JavaScript
the order of the array returned by object.entries() does not depend on how an object is defined. if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));. ...
Object.getOwnPropertyDescriptor() - JavaScript
the object returned is mutable but mutating it has no effect on the original property's configuration. 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. ...
Object.seal() - JavaScript
from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a typeerror (most commonly, although not exclusively, when in strict mode code). the prototype chain remains untouched. however, the __proto__ property is sealed as well. comparison to object.freeze() existing properties in objects frozen with object.freeze() are made immutable. objects sealed with object.seal() can have their existing properties changed. examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, existing properties ...
Object.values() - JavaScript
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. ...
handler.apply() - JavaScript
passed to the apply() method. this is bound to the handler. target the target object. thisarg the this argument for the call. argumentslist the list of arguments for the call. return value the apply() method can return any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { con...
handler.set() - JavaScript
parameters the following parameters are passed to the set() method. this is bound to the handler. target the target object. property the name or symbol of the property to set. value the new value of the property to set. receiver the object to which the assignment was originally directed. this is usually the proxy itself. but a set() handler can also be called indirectly, via the prototype chain or various other ways. for example: suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. that proxy's set() handler will be called, and obj will be passed as the receiver. return value the set() method should return a boolean value. return true to indicate that assignment succeeded. if the se...
ReferenceError - JavaScript
the referenceerror object represents an error when a non-existent variable is referenced. constructor referenceerror() creates a new referenceerror object. instance properties referenceerror.prototype.message error message. although ecma-262 specifies that referenceerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. referenceerror.prototype.name error name. inherited from error. referenceerror.prototype.filename path to file that raised this error. inherited from error. referenceerror.prototype.linenumber line number in file that raised this error. inherited from error. referenceerror.prototype.columnnumber column number in line that raised this error. inherited from error. referenceerror.prototype.stack stack trace. inherited f...
SharedArrayBuffer - JavaScript
ed with a new operator. calling a sharedarraybuffer constructor as a function without new will throw a typeerror. var sab = sharedarraybuffer(1024); // typeerror: calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); constructor sharedarraybuffer() creates a new sharedarraybuffer object. instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array. this is established when the array is constructed and cannot be changed. read only. instance methods sharedarraybuffer.prototype.slice(begin, end) returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive. if either begin or end is negative, it refers to an index from ...
String length - JavaScript
ters, if you want to get the number of characters you need something like this: function getcharacterlength (str) { // the string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getcharacterlength('a\ud87e\udc04z')); // 3 // while not recommended, you could add this to each string as follows: object.defineproperty(string.prototype, 'charlength', { get () { return getcharacterlength(this); } }); console.log('a\ud87e\udc04z'.charlength); // 3 examples basic usage let x = 'mozilla'; let empty = ''; console.log(x + ' is ' + x.length + ' code units long'); /* "mozilla is 7 code units long" */ console.log('the empty string has a length of ' + empty.length); // expected output: "the empty string has a length of 0" ...
Symbol.iterator - JavaScript
d us a pull request. description whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. some built-in types have a default iteration behavior, while other types (such as object) do not. the built-in types with a @@iterator method are: array.prototype[@@iterator]() typedarray.prototype[@@iterator]() string.prototype[@@iterator]() map.prototype[@@iterator]() set.prototype[@@iterator]() see also iteration protocols for more information. property attributes of symbol.iterator writable no enumerable no configurable no examples user-defined iter...
Symbol.match - JavaScript
the symbol.match well-known symbol specifies the matching of a regular expression against a string. this function is called by the string.prototype.match() 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. description this function is also used to identify if objects have the behavior of regular expressions. for example, the methods string.prototype.startswith(), string.prototype.endswith() and string.prototype.includes(), check if their first argument is a regular expression and will throw a typeerror if they are. now, if the match symbol is set to false (or a falsy value), it indicates that the object is not int...
TypedArray.from() - JavaScript
perty and indexed elements); or iterable objects (objects where you can get its elements, such as map and set). typedarray.from() has the optional parameter mapfn, which allows you to execute a map() function on each element of the typed array (or subclass object) that is being created. this means that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)). the length property of the from() method is 1. differences from array.from() some subtle distinctions between array.from() and typedarray.from(): if the thisarg value passed to typedarray.from() is not a constructor, typedarray.from() will throw a typeerror, where array.from() defaults to creating a new array. typedarray.from() uses [[put]] where array.from...
URIError - JavaScript
the urierror object represents an error when a global uri handling function was used in a wrong way. constructor urierror() creates a new urierror object. instance properties urierror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. urierror.prototype.name error name. inherited from error. urierror.prototype.filename path to file that raised this error. inherited from error. urierror.prototype.linenumber line number in file that raised this error. inherited from error. urierror.prototype.columnnumber column number in line that raised this error. inherited from error. urierror.prototype.stack stack trace. inherited from error. examples catching an urierror...
WeakRef - JavaScript
es to it, the javascript engine's garbage collector may destroy the object and reclaim its memory. if that happens, you can't get the object from a weak reference anymore. note: please see the avoid where possible section below. correct use of weakref takes careful thought, and it's best avoided if possible. constructor weakref() creates a new weakref object. instance methods weakref.prototype.deref() returns the weakref object's target object, or undefined if the target object has been reclaimed. avoid where possible correct use of weakref takes careful thought, and it's best avoided if possible. it's also important to avoid relying on any specific behaviors not guaranteed by the specification. when, how, and whether garbage collection occurs is down to the implementation of any g...
WeakSet - JavaScript
first run, and passed along with every subsequent function call (using the internal _refs parameter). the number of objects or their traversal order is immaterial, so a weakset is more suitable (and performant) than a set for tracking object references, especially if a very large number of objects is involved. constructor weakset() creates a new weakset object. instance methods weakset.prototype.add(value) appends value to the weakset object. weakset.prototype.delete(value) removes value from the weakset. weakset.prototype.has(value) will return false afterwards. weakset.prototype.has(value) returns a boolean asserting whether value is present in the weakset object or not. examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ...
WebAssembly.Instance - JavaScript
a webassembly.instance object is a stateful, executable instance of a webassembly.module. instance objects contain all the exported webassembly functions that allow calling into webassembly code from javascript. constructor webassembly.instance() creates a new instance object. instance properties instance.prototype.exports returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. read-only. examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); ...
WebAssembly.Memory - JavaScript
the webassembly.memory object is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance. a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. constructor webassembly.memory() creates a new memory object. instance properties memory.prototype.buffer an accessor property that returns the buffer contained in the memory. instance methods memory.prototype.grow() increases the size of the memory instance by a specified number of webassembly pages (each one is 64kb in size). examples creating a new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a new webas...
WebAssembly.Table() constructor - JavaScript
e object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.was...
class expression - JavaScript
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. ...
typeof - JavaScript
avoid them. typeof new boolean(true) === 'object'; typeof new number(1) === 'object'; typeof new string('abc') === 'object'; ...
yield - JavaScript
orresult is returned to the caller in which the value is the value specified by the return statement and done is true. if an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to generator.prototype.next(), generators offer enormous power and control. unfortunately, next() is asymmetric, but that can’t be helped: it always sends a value to the currently suspended yield, but returns the operand of the following yield. examples using yield the following code is the declaration of an example generator function. function* countapplesales () { let salelist = [3, 7, 5] for (let i = 0;...
class - JavaScript
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. you can also define a class using a class expression. but unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a syntaxerror if attempted. syntax class name [extends othername] { // class body } description the class body of a class declaration is executed in strict mode. the constructor method is optional. ...
import.meta - JavaScript
pt module. it contains information about the module, like the module's url. syntax import.meta description the syntax consists of the keyword import, a dot, and the identifier meta. normally the left-hand side of the dot is the object on which property access is performed, but here import is not really an object. the import.meta object is created by the ecmascript implementation, with a null prototype. the object is extensible, and its properties are writable, configurable, and enumerable. examples using import.meta given a module my-module.js <script type="module" src="my-module.js"></script> you can access meta information about the module using the import.meta object. console.log(import.meta); // { url: "file:///home/user/my-module.js" } it returns an object with a url property indi...
let - JavaScript
obal" console.log(this.y); // undefined emulating private members in dealing with constructors it is possible to use the let bindings to share one or more private members without using closures: var thing; { let privatescope = new weakmap(); let counter = 0; thing = function() { this.someproperty = 'foo'; privatescope.set(this, { hidden: ++counter, }); }; thing.prototype.showpublic = function() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variab...
with - JavaScript
using with may not be forward compatible, especially when used with something other than a plain object. consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj. however, ecmascript 2015 introduces a values property on array.prototype (so that it will be available on every array). so, in a javascript environment that supports ecmascript 2015, the values reference inside the with statement could resolve to [1,2,3].values. however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object. if it were not, one can see how this would be a difficult issue to debug. examples using w...
Strict mode - JavaScript
the normal code may duplicate property names, with the last one determining the property's value. but since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the las...
Trailing commas - JavaScript
on, however, disallows trailing commas. syntax , examples trailing commas in literals arrays javascript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 if more than one trailing comma is used, an elision (or hole) is produced. an array with holes is called sparse (a dense array has no holes). when iterating arrays for example with array.prototype.foreach() or array.prototype.map(), array holes are skipped. var arr = [1, 2, 3,,,]; arr.length; // 5 objects starting with ecmascript 5, trailing commas in object literals are legal as well: var object = { foo: "bar", baz: "qwerty", age: 42, }; trailing commas in functions ecmascript 2017 allows trailing commas in function parameter lists. parameter definitions the following funct...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
es/js13kpwa/icons/icon-128.png', '/pwa-examples/js13kpwa/icons/icon-168.png', '/pwa-examples/js13kpwa/icons/icon-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; next, the links to images to be loaded along with the content from the data/games.js file are generated in the second array. after that, both arrays are merged using the array.prototype.concat() function. var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventlistener('install', (e) => { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then((cache) => { console...
The building blocks of responsive design - Progressive web apps (PWAs)
and basics. fluid grids the best place to start is with fluid measurements for our application layout — essentially, this means using a combination of percentages and ems/rems to size your containers and text, not fixed widths such as pixels. this has a lot of advantages in that the layout will adapt to different viewport dimensions. let's look at an example. we've written a simple-but-fun prototype for an application called snapshot, which takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery. you can then view previously-captured images and delete them. other articles will discuss the functionality in more detail, but here we're interested in the layout. note: you can find t...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
oke() methods partially implemented (bug 1239100). the methods ispointinfill() and ispointinstroke() are not implemented yet (bug 1325319). ...
Using custom elements - Web Components
file defines a class called popupinfo, which extends the generic htmlelement class. class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // write element functionality in here ... } } the preceding code snippet contains the constructor() definition for the class, which always starts by calling super() so that the correct prototype chain is established. inside the constructor, we define all the functionality the element will have when an instance of it is instantiated. in this case we attach a shadow root to the custom element, use some dom manipulation to create the element's internal shadow dom structure — which is then attached to the shadow root — and finally attach some css to the shadow root to style it. // crea...