Search completed in 1.02 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.
... 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.
...And 6 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).
...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.
...And 78 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.
... objective: to understand javascript object prototypes, how prototype chains work, and how to add new methods onto the prototype property.
...And 48 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.
...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).
... 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.
...And 30 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.
...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.
...And 20 more matches
Object.setPrototypeOf() - JavaScript
the object.setprototypeof() method sets the prototype (i.e., the internal [[prototype]] 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.
...And 16 more matches
Function.prototype.bind() - JavaScript
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.
... // does not work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var slice = array.prototype.slice; function.prototype.bind = function() { var thatfunc = this, thatarg = arguments[0]; var args = slice.call(arguments, 1); if (typeof thatfunc !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - ' + 'what is trying to be bound is not callable'); } return function(){ var funcarg...
... // yes, it does work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var arrayprototypeslice = array.prototype.slice; function.prototype.bind = function(otherthis) { if (typeof this !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - what is trying to be bound is not callable'); } var baseargs= arrayprototypeslice.call(arguments, 1), ...
...And 11 more matches
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.
... syntax reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype.
...And 9 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.
... obj js::handleobject object for which to retrieve the prototype.
...And 8 more matches
handler.setPrototypeOf() - JavaScript
the handler.setprototypeof() method is a trap for object.setprototypeof().
... syntax const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method.
... prototype the object's new prototype or null.
...And 8 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.
... proto js::handleobject the object to set as the new prototype of obj.
...And 7 more matches
Object.prototype.toSource() - JavaScript
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.
...And 6 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.
...And 6 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.
...*/ } 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 perform the last line here?
...*/ } 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.
...And 5 more matches
handler.getPrototypeOf() - JavaScript
the handler.getprototypeof() method is a trap for the [[getprototypeof]] internal method.
... syntax const p = new proxy(obj, { getprototypeof(target) { ...
... } }); parameters the following parameter is passed to the getprototypeof() method.
...And 5 more matches
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.
... key jsprotokey the key of the prototype.
...And 4 more matches
RegExp.prototype[@@replace]() - JavaScript
a number of special replacement patterns are supported; see the specifying a string as a parameter section in string.prototype.replace() page.
...the arguments supplied to this function are described in the specifying a function as a parameter section in string.prototype.replace() page.
... description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object.
...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.
... proto js::handle&lt;jsobject*&gt; pointer to the prototype object.
...And 3 more matches
TextEncoder.prototype.encodeInto() - Web APIs
the textencoder.prototype.encodeinto() method 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.
...the solution is typedarray.prototype.subarray().
...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.
...And 3 more matches
Array.prototype.find() - JavaScript
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().
... if you need to find if any element satisfies the provided testing function, use array.prototype.some().
...And 3 more matches
Array.prototype.forEach() - JavaScript
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.
...[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 following is just one way and is presented to explain how array.prototype.foreach() works by using ecmascript 5 object.* meta property functions.
...And 3 more matches
Array.prototype.map() - JavaScript
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 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.
...And 3 more matches
Array.prototype.toLocaleString() - JavaScript
options optional an object with configuration properties, for numbers see number.prototype.tolocalestring(), and for dates see date.prototype.tolocalestring().
... polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!array.prototype.tolocalestring) { object.defineproperty(array.prototype, 'tolocalestring', { value: function(locales, options) { // 1.
... 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.
...And 3 more matches
Object.getPrototypeOf() - JavaScript
the object.getprototypeof() method returns the prototype (i.e.
... the value of the internal [[prototype]] property) of the specified object.
... syntax object.getprototypeof(obj) parameters obj the object whose prototype is to be returned.
...And 3 more matches
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.
... forobj js::handleobject an object from the global whose array.prototype is being retrieved.
...And 2 more matches
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.
... forobj js::handleobject an object from the global whose function.prototype is being retrieved.
...And 2 more matches
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.
... forobj js::handleobject an object from the global whose object.prototype is being retrieved.
...And 2 more matches
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
message warning: string.charat is deprecated; use string.prototype.charat instead warning: string.charcodeat is deprecated; use string.prototype.charcodeat instead warning: string.concat is deprecated; use string.prototype.concat instead warning: string.contains is deprecated; use string.prototype.contains instead warning: string.endswith is deprecated; use string.prototype.endswith instead warning: string.includes is deprecated; use string.prototype.includes instead warning: string.indexof is deprecated; use string.prototype.indexof...
... instead warning: string.lastindexof is deprecated; use string.prototype.lastindexof instead warning: string.localecompare is deprecated; use string.prototype.localecompare instead warning: string.match is deprecated; use string.prototype.match instead warning: string.normalize is deprecated; use string.prototype.normalize instead warning: string.replace is deprecated; use string.prototype.replace instead warning: string.search is deprecated; use string.prototype.search instead warning: string.slice is deprecated; use string.prototype.slice instead warning: string.split is deprecated; use string.prototype.split instead warning: string.starts...
...with is deprecated; use string.prototype.startswith instead warning: string.substr is deprecated; use string.prototype.substr instead warning: string.substring is deprecated; use string.prototype.substring instead warning: string.tolocalelowercase is deprecated; use string.prototype.tolocalelowercase instead warning: string.tolocaleuppercase is deprecated; use string.prototype.tolocaleuppercase instead warning: string.tolowercase is deprecated; use string.prototype.tolowercase instead warning: string.touppercase is deprecated; use string.prototype.touppercase instead warning: string.trim is deprecated; use string.prototype.trim instead warning: string.trimleft is deprecated; use string.pro...
...And 2 more matches
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.
... the non-standard date.prototype.tolocaleformat method is deprecated and shouldn't be used anymore.
...And 2 more matches
Function.prototype.apply() - JavaScript
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.
... for alternative methods, please consider one of the following approaches: using object.__proto__: function.prototype.construct = function (aargs) { let onew = {}; onew.__proto__ = this.prototype; this.apply(onew, aargs); return onew; }; using closures: function.prototype.construct = function(aargs) { let fconstructor = this, fnewconstr = function() { fconstructor.apply(this, aargs); }; fnewconstr.prototype = fconstructor.prototype; return new fnewconstr(); }; using the function constructor: function.prototype.construct = function (aargs) { let fnewconstr = new function(""); fnewconstr.prototype = this.prototype; let onew = new fnewconstr(); this.apply(onew, aargs); return onew; }; example usage: function myconstructor() { for (let nprop = 0; nprop < argum...
...in these cases you have to use the function.prototype.bind method.
...And 2 more matches
Function.prototype.toString() - JavaScript
description the function object overrides the tostring method inherited from object; it does not inherit object.prototype.tostring.
... 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.
... function.prototype.tostring.call('foo'); // typeerror if the tostring() method is called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.
...And 2 more matches
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.
... description js_geterrorprototype returns the original value of error.prototype from the global object of the current compartment of cx.
... see also mxr id search for js_geterrorprototype bug 997285 ...
Array.prototype[@@unscopables] - JavaScript
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.
...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.reduce() - JavaScript
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'); ...
... 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.
..., fn) => fn(acc), input ) // composed functions for multiplication of specific values const multiply6 = pipe(double, triple) const multiply9 = pipe(triple, triple) const multiply16 = pipe(quadruple, quadruple) const multiply24 = pipe(double, triple, quadruple) // usage multiply6(6) // 36 multiply9(9) // 81 multiply16(16) // 256 multiply24(10) // 240 write map using reduce if (!array.prototype.mapusingreduce) { array.prototype.mapusingreduce = function(callback, thisarg) { return this.reduce(function(mappedarray, currentvalue, index, array) { mappedarray[index] = callback.call(thisarg, currentvalue, index, array) return mappedarray }, []) } } [1, 2, , 3].mapusingreduce( (currentvalue, index, array) => currentvalue + index + array.length ) // [5, 7, , 10] s...
...pecifications specification ecmascript (ecma-262)the definition of 'array.prototype.reduce()' in that specification.
Array.prototype.every() - JavaScript
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.
... if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw new typeerror(); } // 5.
...-------------- arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr.pop() console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) // loop runs for 2 iterations only, as the remaining // items are `pop()`ed off // // 1st iteration: [1,2,3][0] -> 1 // 2nd iteration: [1,2][1] -> 2 specifications specification ecmascript (ecma-262)the definition of 'array.prototype.every' in that specification.
Array.prototype.indexOf() - JavaScript
note: for the string method, see string.prototype.indexof().
...if (!array.prototype.indexof) array.prototype.indexof = (function(object, max, min) { "use strict" return function indexof(member, fromindex) { if (this === null || this === undefined) throw typeerror("array.prototype.indexof called on null or undefined") var that = object(this), len = that.length >>> 0, i = min(fromindex | 0, len) if (i < 0) i = max(0, len + i) else if (i >...
... // production steps of ecma-262, edition 5, 15.4.4.14 // reference: http://es5.github.io/#x15.4.4.14 if (!array.prototype.indexof) { array.prototype.indexof = function(searchelement, fromindex) { "use strict"; var k; // 1.
... specifications specification ecmascript (ecma-262)the definition of 'array.prototype.indexof' in that specification.
Array.prototype.push() - JavaScript
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.
...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.
... specifications specification ecmascript (ecma-262)the definition of 'array.prototype.push' in that specification.
Date.prototype.toString() - JavaScript
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 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.
... 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.
Intl.NumberFormat.prototype.formatToParts() - JavaScript
the intl.numberformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by numberformat formatters.
... syntax intl.numberformat.prototype.formattoparts(number) parameters number optional a number or bigint to format.
...for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
... console.log(numberstring); // "3.500,00 <strong>€</strong>" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.formattoparts' in that specification.
Object.prototype.hasOwnProperty() - JavaScript
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.
...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.
... an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and call it with 'this' set to foo ({}).hasownproperty.call(foo, 'bar'); // true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.call(foo, 'bar'); // true note that in the last case there are no newly created objects.
... specifications specification ecmascript (ecma-262)the definition of 'object.prototype.hasownproperty' in that specification.
Object.prototype.toString() - JavaScript
dog.prototype.tostring = function dogtostring() { const ret = 'dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } or, using es6 template strings: dog.prototype.tostring = function dogtostring() { return `dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`; } with the preceding code in place, any time thedog is used in a string context, javascript ...
... to use the object.prototype.tostring() with every object, you need to call function.prototype.call() or function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisarg).
... const tostring = object.prototype.tostring; tostring.call(new date); // [object date] tostring.call(new string); // [object string] tostring.call(math); // [object math] // since javascript 1.8.5 tostring.call(undefined); // [object undefined] tostring.call(null); // [object null] using tostring() in this way is unreliable; objects can change the behavior of object.prototype.tostring() by defining a symbol.tostringtag property, leading to unexpected results.
... for example: const mydate = new date(); object.prototype.tostring.call(mydate); // [object date] mydate[symbol.tostringtag] = 'mydate'; object.prototype.tostring.call(mydate); // [object mydate] date.prototype[symbol.tostringtag] = 'prototype polluted'; object.prototype.tostring.call(new date()); // [object prototype polluted] specifications specification ecmascript (ecma-262)the definition of 'object.prototype.tostring' in that specification.
Object.prototype.valueOf() - JavaScript
when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method.
...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.
... examples using valueof on custom types function mynumbertype(n) { this.number = n; } mynumbertype.prototype.valueof = function() { return this.number; }; var myobj = new mynumbertype(4); myobj + 3; // 7 using unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{} // nan +[] // 0 (tostring() returns an empty string list) +[1] // 1 +[1,2] // nan +new set([1]) // nan +...
...bigint(1) // uncaught typeerror: cannot convert a bigint value to a number +undefined // nan +null // 0 +true // 1 +false // 0 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.valueof' in that specification.
Promise.prototype.catch() - JavaScript
it behaves the same as calling promise.prototype.then(undefined, onrejected) (in fact, calling obj.catch(onrejected) internally calls obj.then(undefined, onrejected)).
... return value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler.
... demonstration of the internal call: // overriding original promise.prototype.then/catch just to add some logs (function(promise){ var originalthen = promise.prototype.then; var originalcatch = promise.prototype.catch; promise.prototype.then = function(){ console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); return originalthen.apply(this, arguments); }; promise.prototype.catch = function(){ console.
...rror("catch p1!"); console.error(reason); }); p2.then(function (value) { console.log("next promise's onfulfilled"); /* next promise's onfulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onrejected"); console.log(reason); }); specifications specification ecmascript (ecma-262)the definition of 'promise.prototype.catch' in that specification.
RegExp.prototype[@@match]() - JavaScript
description this method is called internally in string.prototype.match().
... 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.
... 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 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@match]' in that specification.
RegExp.prototype[@@matchAll]() - JavaScript
description this method is called internally in string.prototype.matchall().
... 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.
... for example, to return an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { return null; } else { return array.from(result); } } } const re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '2016-01-02|2019-03-07'; const result = str.matchall(re); console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ] console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ] specific...
...ations specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@matchall]' in that specification.
RegExp.prototype[@@search]() - JavaScript
description this method is called internally in string.prototype.search().
... 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.
... 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[@@split]() - JavaScript
description this method is called internally in string.prototype.split() if its separator argument is an object that has a @@split method, such as a regexp.
... examples direct call this method can be used in almost the same way as string.prototype.split(), except the different this and the different order of arguments.
... 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.
Date.prototype.toLocaleFormat() - Archive of obsolete content
see also the newer version of date.prototype.tolocaledatestring().
...see warning: date.prototype.tolocaleformat is deprecated for more information and migration help.
... 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.
Object.prototype.__noSuchMethod__ - Archive of obsolete content
the second argument is an actual array (that is, it inherits through the array.prototype chain) and not the array-like arguments object.
... // 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, age, address){ addparent(this, namedthing.prototype); namedthing.call(this, name); addparent(this, agedthing.prototype); agedthing.call(this, age); this.address = address; } person.prototype = { getaddr: function() { return this.address; }, setaddr: function(addr) { this.address = addr; } } var bob = new person('bob', 25, 'new york'); console.log('getage is ' + (('getage' in bob) ?
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.
TypeError: X.prototype.y called on incompatible type - JavaScript
message typeerror: 'this' is not a set object (edge) typeerror: function.prototype.tostring called on incompatible object (firefox) typeerror: function.prototype.bind called on incompatible target (firefox) typeerror: method set.prototype.add called on incompatible receiver undefined (chrome) typeerror: bind must be called on a function (chrome) error type typeerror what went wrong?
... this issue can arise when using the function.prototype.call() or function.prototype.apply() methods, and providing a this argument which does not have the expected type.
...to work-around this issue, you will either need to provide a lambda which is making the call, or use the function.prototype.bind() function to force the this argument to the expected object.
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.
... function logiterable(it) { if (!(symbol.iterator in object.getprototypeof(it) /* or "symbol.iterator in object.__proto__" or "it[symbol.iterator]" */)) { console.log(it, ' is not an iterable object...'); return; } var iterator = it[symbol.iterator](); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of iterator) { console.log(letter); } } // array logiterable(['a', 'b', 'c']); // a // b // c // string logiterable('abc'); // a // b // c logiterable(123); // 123 " is not an iterable object..." specifications specification ecmascript (ecma-262)the definition of 'array.prototype[@@iterator...
Array.prototype.reduceRight() - JavaScript
see also array.prototype.reduce() for left-to-right.
... // production steps of ecma-262, edition 5, 15.4.4.22 // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'undefined' === typeof this) { throw new typeerror('array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw new typeerror(callback + ' is not a function'); } var t = object(this), len = t.length >>...
...rgs.reduceright((acc, fn) => fn(acc), value) // increment passed number const inc = (n) => n + 1 // doubles the passed value const double = (n) => n * 2 // using composition function console.log(compose(double, inc)(2)); // 6 // using composition function console.log(compose(inc, double)(2)); // 5 specifications specification ecmascript (ecma-262)the definition of 'array.prototype.reduceright' in that specification.
Array.prototype.fill() - JavaScript
polyfill if (!array.prototype.fill) { object.defineproperty(array.prototype, 'fill', { value: function(value) { // steps 1-2.
... 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.
... // [1, 2, 3] array(3).fill(4) // [4, 4, 4] [].fill.call({ length: 3 }, 4) // {0: 4, 1: 4, 2: 4, length: 3} // a single object, referenced by each slot of the array: let arr = array(3).fill({}) // [{}, {}, {}] arr[0].hi = "hi" // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.fill' in that specification.
Array.prototype.filter() - JavaScript
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.
... if (!array.prototype.filter){ array.prototype.filter = function(func, thisarg) { 'use strict'; if ( !
...t', 'exuberant', 'destruction', 'elite', 'present'] const deletewords = words.filter( (word, index, arr) => { arr.pop() return word.length < 6 }) console.log(deletewords) // notice 'elite' is not even obtained as its been popped off `words` before filter can even get there // ["spray" ,"limit"] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.filter' in that specification.
Array.prototype.findIndex() - JavaScript
polyfill // https://tc39.github.io/ecma262/#sec-array.prototype.findindex if (!array.prototype.findindex) { object.defineproperty(array.prototype, 'findindex', { value: function(predicate) { // 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.
...function the following example finds the index of a fruit using an arrow function: const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findindex(fruit => fruit === "blueberries"); console.log(index); // 3 console.log(fruits[index]); // blueberries specifications specification ecmascript (ecma-262)the definition of 'array.prototype.findindex' in that specification.
Array.prototype.some() - JavaScript
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().
... // production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.github.io/#x15.4.4.17 if (!array.prototype.some) { array.prototype.some = function(fun, thisarg) { 'use strict'; if (this == null) { throw new typeerror('array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new typeerror(); } var t = object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisarg, t[i], i, t)) { return true; } } return false; }; } examples testing value of array elements the following example tests whether any element in the array is bigger than 10.
...n(value) { 'use strict'; if (typeof value === 'string') { value = value.tolowercase().trim(); } return truthy_values.some(function(t) { return t === value; }); } getboolean(false); // false getboolean('false'); // false getboolean(1); // true getboolean('true'); // true specifications specification ecmascript (ecma-262)the definition of 'array.prototype.some' in that specification.
Array.prototype.values() - JavaScript
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].
... array.prototype.values === array.prototype[symbol.iterator] //true iteration using .next() var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // object { value: "d", done: false } iterator.next(); // object { value: "e", done: false } iterator.next(); // object { value: undefined, done: true } iteraror.next().value; // undefined one-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter ...
... specifications specification ecmascript (ecma-262)the definition of 'array.prototype.values' in that specification.
Error.prototype.toString() - JavaScript
description the error object overrides the object.prototype.tostring() method inherited by all objects.
... its semantics are as follows (assuming object and string have their original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ?
...r'); console.log(e.tostring()); // 'error: fatal error' e.name = undefined; console.log(e.tostring()); // 'error: fatal error' e.name = ''; console.log(e.tostring()); // 'fatal error' e.message = undefined; console.log(e.tostring()); // '' e.name = 'hello'; console.log(e.tostring()); // 'hello' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.tostring' in that specification.
Intl.Collator.prototype.compare() - JavaScript
the intl.collator.prototype.compare() method compares two strings according to the sort order of this collator object.
...note that the function is bound to the collator from which it was obtained, so it can be passed directly to array.prototype.sort().
... ['congrès', 'congres', 'assemblée', 'poisson']; var collator = new intl.collator('fr', { usage: 'search', sensitivity: 'base' }); var s = 'congres'; var matches = a.filter(v => collator.compare(v, s) === 0); console.log(matches.join(', ')); // → "congrès, congres" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.compare' in that specification.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the intl.datetimeformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by datetimeformat formatters.
...for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
...opts); let date = date.utc(2012, 11, 17, 3); df.formattoparts(date) // return value [ { type: 'month', value: '11' }, { type: 'literal', value: '/' }, { type: 'day', value: '4' }, { type: 'literal', value: '/' }, { type: 'relatedyear', value: '2012' } ] specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat.prototype.formattoparts' in that specification.
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
the intl.listformat.prototype.formattoparts() method 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.
... 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.
Intl.NumberFormat.prototype.format() - JavaScript
the intl.numberformat.prototype.format() method formats a number according to the locale and formatting options of this numberformat object.
...note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map.
... 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.
Number.prototype.toLocaleString() - JavaScript
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.
...matting var num = 30000.65; console.log(num.tolocalestring(undefined, {minimumfractiondigits: 2, maximumfractiondigits: 2})); // → "30,000.65" where english is the default language, or // → "30.000,65" where german is the default language, or // → "30 000,65" where french is the default language specifications specification ecmascript (ecma-262)the definition of 'number.prototype.tolocalestring' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'number.prototype.tolocalestring' in that specification.
Number.prototype.toPrecision() - JavaScript
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().
...00123' console.log(numobj.toprecision(5)) // logs '0.00012300' console.log(numobj.toprecision(2)) // logs '0.00012' console.log(numobj.toprecision(1)) // logs '0.0001' // note that exponential notation might be returned in some circumstances console.log((1234.5).toprecision(2)) // logs '1.2e+3' specifications specification ecmascript (ecma-262)the definition of 'number.prototype.toprecision' in that specification.
Object.prototype.propertyIsEnumerable() - JavaScript
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.
...inherited properties var a = []; a.propertyisenumerable('constructor'); // returns false function firstconstructor() { this.property = 'is not enumerable'; } firstconstructor.prototype.firstmethod = function() {}; function secondconstructor() { this.method = function() { return 'is enumerable'; }; } secondconstructor.prototype = new firstconstructor; secondconstructor.prototype.constructor = secondconstructor; var o = new secondconstructor(); o.arbitraryproperty = 'is enumerable'; o.propertyisenumerable('arbitraryproperty'); // returns true o.propertyisenumerable('metho...
...d'); // returns true o.propertyisenumerable('property'); // returns false o.property = 'is enumerable'; o.propertyisenumerable('property'); // returns true // these return false as they are on the prototype which // propertyisenumerable does not consider (even though the last two // are iteratable with for-in) o.propertyisenumerable('prototype'); // returns false (as of js 1.8.1/ff3.6) o.propertyisenumerable('constructor'); // returns false o.propertyisenumerable('firstmethod'); // returns false specifications specification ecmascript (ecma-262)the definition of 'object.prototype.propertyisenumerable' in that specification.
Promise.prototype.then() - JavaScript
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.
...lled console.error('rejected', e); }); var p3 = p1.then(function() { // return promise here, that will be rejected with 'error' after 1 second return new promise(rejectlater); }); p3.then(function(v) { // not called console.log('resolved', v); }, function(e) { console.error('rejected', e); // "rejected", 'error' }); window.setimmediate style promise-based polyfill using a function.prototype.bind() reflect.apply (reflect.apply()) method to create a (non-cancellable) window.setimmediate-style function.
...promise.resolve(args).then(rfab(null, fn, null)) : nexttickpromise(), undefined ); nexttick.ntp = nexttickpromise; return nexttick; })(); specifications specification ecmascript (ecma-262)the definition of 'promise.prototype.then' in that specification.
RegExp.prototype.exec() - JavaScript
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.
RegExp.prototype.test() - JavaScript
test() returns a boolean, unlike the string.prototype.search() method (which returns the index of a match, or -1 if not found).
...(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.
...(regexp.prototype.exec() also advances the lastindex property.) further calls to test(str) will resume searching str starting from lastindex.
SharedArrayBuffer.prototype.slice() - JavaScript
the sharedarraybuffer.prototype.slice() method returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
...this method has the same algorithm as array.prototype.slice().
... 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.codePointAt() - JavaScript
https://mths.be/codepointat v0.2.0 by @mathias */ if (!string.prototype.codepointat) { (function() { 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` var defineproperty = (function() { // ie 8 only supports `object.defineproperty` on dom elements try { var object = {}; var $defineproperty = object.defineproperty; var result = $defineproperty(object, object, object) && $defineproperty; } catc...
... 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 ...
...'\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).tostring(16)) } // '1f40e', '1f471', '2764' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.codepointat' in that specification.
String.prototype.match() - JavaScript
if you want to obtain capture groups and the global flag is set, you need to use regexp.exec() or string.prototype.matchall() instead.
... 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.
...returns ["65"] str3.match(null); // returns ["null"] specifications specification ecmascript (ecma-262)the definition of 'string.prototype.match' in that specification.
String.prototype.toString() - JavaScript
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.toUpperCase() - JavaScript
exceptions typeerror when called on null or undefined, for example, string.prototype.touppercase.call(undefined).
... 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.trimStart() - JavaScript
aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart.
...in some engines this means: string.prototype.trimleft.name === "trimstart"; polyfill //https://github.com/fabiovergani/js-polyfill_string-trimstart (function(w){ var string=w.string, proto=string.prototype; (function(o,p){ if(p in o?o[p]?false:true:true){ var r=/^\s+/; o[p]=o.trimleft||function(){ return this.replace(r,'') } } })(proto,'trimstart'); })(window); /* es6: (w=>{ const string=w.string, proto=string.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimleft||function(){ return this.replace(r,'') } } })(proto,'tr...
...imstart'); })(window); */ examples using trimstart() the following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimstart(); console.log(str.length); // 5 console.log(str); // 'foo ' specifications specification ecmascript (ecma-262)the definition of ' string.prototype.trimstart' in that specification.
Symbol.prototype.description - JavaScript
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.
...ption; // "" symbol().description; // undefined // well-known symbols symbol.iterator.tostring(); // "symbol(symbol.iterator)" symbol.iterator.description; // "symbol.iterator" // global symbols symbol.for('foo').tostring(); // "symbol(foo)" symbol.for('foo').description; // "foo" specifications specification ecmascript (ecma-262)the definition of 'get symbol.prototype.description' in that specification.
TypedArray.prototype.copyWithin() - JavaScript
this method has the same algorithm as array.prototype.copywithin.
... 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.prototype.copywithin' in that specification.
TypedArray.prototype.fill() - JavaScript
this method has the same algorithm as array.prototype.fill().
...use the following "polyfill" along with the array.prototype.fill() polyfill.
... // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; } examples using fill new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4] new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4] new uint8array([1, 2, 3]).fill(4, 1, 2); // uint8array [1, 4, 3] new uint8array([1, 2, 3]).fill(4, 1, 1); // uint8array [1, 2, 3] new uint8array([1, 2, 3]).fill(4, -3, -2); // uint8array [4, 2, 3] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.fill' in that specification.
TypedArray.prototype.join() - JavaScript
this method has the same algorithm as array.prototype.join().
... // 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.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
this method has the same algorithm as array.prototype.reduce().
... 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
this method has the same algorithm as array.prototype.slice().
... 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.
... 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
this method has the same algorithm as array.prototype.some().
... // 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.
... new uint8array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false new uint8array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.some' in that specification.
TypedArray.prototype.sort() - JavaScript
this method has the same algorithm as array.prototype.sort(), except that sorts the values numerically instead of as strings.
... examples using sort for more examples, see also the array.prototype.sort() method.
... // regular arrays require a compare function to sort numerically: numbers = [40, 1, 5, 200]; numbers.sort(); // [1, 200, 40, 5] numbers.sort((a, b) => a - b); // compare numbers // [ 1, 5, 40, 200 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.sort' in that specification.
WebAssembly.Table.prototype.set() - JavaScript
the set() prototype method of the webassembly.table object mutates a reference stored at a given index to a different value.
... exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown.
...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).
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.
... learn more general knowledge prototype-based programming on wikipedia ...
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.
... see inheritance and the prototype chain learn more general knowledge software prototyping on wikipedia ...
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
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...
...y implement nodelist.prototype.foreach() (chrome, for example).
TextEncoder.prototype.encode() - Web APIs
the textencoder.prototype.encode() method takes a usvstring as input, and returns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object.
...">encoded result: </p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of 'textencoder.prototype.encode()' in that specification.
Array.prototype.copyWithin() - JavaScript
polyfill if (!array.prototype.copywithin) { object.defineproperty(array.prototype, 'copywithin', { value: function(target, start/*, end*/) { // steps 1-2.
...: 1, length: 5} // es2015 typed arrays are subclasses of array var i32a = new int32array([1, 2, 3, 4, 5]) i32a.copywithin(0, 2) // int32array [3, 4, 5, 4, 5] // on platforms that are not yet es2015 compliant: [].copywithin.call(new int32array([1, 2, 3, 4, 5]), 0, 3, 4); // int32array [4, 2, 3, 4, 5] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.copywithin' in that specification.
Array.prototype.flatMap() - JavaScript
description see array.prototype.map() for a detailed description of the callback function.
...[n] : [n-1, 1] ) // expected output: [4, 1, 4, 20, 16, 1, 18] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.flatmap' in that specification.
Array.prototype.includes() - JavaScript
(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)the definition of 'array.prototype.includes' in that specification.
Array.prototype.join() - JavaScript
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.lastIndexOf() - JavaScript
// production steps of ecma-262, edition 5, 15.4.4.15 // reference: http://es5.github.io/#x15.4.4.15 if (!array.prototype.lastindexof) { array.prototype.lastindexof = function(searchelement /*, fromindex*/) { 'use strict'; if (this === void 0 || this === null) { throw new typeerror(); } var n, k, t = object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length > 1) { n = number(arguments[1]); if (n != n) {...
... specifications specification ecmascript (ecma-262)the definition of 'array.prototype.lastindexof' in that specification.
Array.prototype.pop() - JavaScript
array.prototype.shift() has similar behavior to pop, but applied to the first element in an array.
... 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
array.prototype.pop() has similar behavior to shift, but applied to the last element in an array.
...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.
Array.prototype.slice() - JavaScript
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.
... 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.
Array.prototype.toString() - JavaScript
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.
BigInt.prototype.toLocaleString() - JavaScript
nese yen doesn't use a minor unit console.log(bigint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' })) // → ï¿¥123,456,789,123,456,789 // limit to three significant digits console.log(bigint.tolocalestring('en-in', { maximumsignificantdigits: 3 })); // → 1,23,00,00,00,00,00,00,000 specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.tolocalestring()' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'bigint.prototype.tolocalestring()' in that specification.
BigInt.prototype.toString() - JavaScript
description the bigint object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring().
... (-0n).tostring(); // '0' bigint(-0).tostring(); // '0' specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.tostring()' in that specification.
Boolean.prototype.toString() - JavaScript
description the boolean object overrides the tostring method of the object object; it does not inherit object.prototype.tostring().
... 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
for the day of the month, see date.prototype.getdate().
...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.toISOString() - JavaScript
engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.prototype.toisostring) { (function() { function pad(number) { if (number < 10) { return '0' + number; } return number; } date.prototype.toisostring = function() { return this.getutcfullyear() + '-' + pad(this.getutcmonth() + 1) + '-' + pad(this.getutcdate()) + 't' + pad(this.getutchours()) + ':' + pad(this.getutcminutes()) + ...
... specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toisostring' in that specification.
Date.prototype.toLocaleDateString() - JavaScript
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.toLocaleString() - JavaScript
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
en the us needs 24-hour time console.log(date.tolocaletimestring('en-us', { hour12: false })); // → "19:00:00" // show only hours and minutes, use options with the default locale - use an empty array console.log(date.tolocaletimestring([], { hour: '2-digit', minute: '2-digit' })); // → "20:01" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocaletimestring' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'date.prototype.tolocaletimestring' in that specification.
Date.prototype.valueOf() - JavaScript
this method is functionally equivalent to the date.prototype.gettime() method.
... 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 combined with the name 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('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of 'error.prototype.message' in that specification.
Error.prototype.name - JavaScript
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.
Intl.Collator.prototype.resolvedOptions() - JavaScript
the intl.collator.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and collation options computed during initialization of this collator object.
... = de.resolvedoptions(); usedoptions.locale; // "de" usedoptions.usage; // "sort" usedoptions.sensitivity; // "base" usedoptions.ignorepunctuation; // false usedoptions.collation; // "default" usedoptions.numeric; // false specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.resolvedoptions' in that specification.
Intl.DateTimeFormat.prototype.format() - JavaScript
the intl.datetimeformat.prototype.format() method formats a date according to the locale and formatting options of this intl.datetimeformat object.
...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().
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.
... 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.
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.
... 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.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.datetimeformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this datetimeformat object.
...: 'utc' }); var usedoptions = germanfakeregion.resolvedoptions(); usedoptions.locale; // "de" usedoptions.calendar; // "gregory" usedoptions.numberingsystem; // "latn" usedoptions.timezone; // "utc" usedoptions.month; // "numeric" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat.prototype.resolvedoptions' in that specification.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
the intl.numberformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and number formatting options computed during initialization of this numberformat object.
..."standard" usedoptions.signdisplay; // "auto" usedoption.style; // "decimal" usedoptions.minimumintegerdigits; // 1 usedoptions.minimumfractiondigits; // 0 usedoptions.maximumfractiondigits; // 3 usedoptions.usegrouping; // true specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.resolvedoptions' in that specification.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
the intl.pluralrules.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this pluralrules object.
...s.locale; // "de-de" usedoptions.maximumfractiondigits; // 3 usedoptions.minimumfractiondigits; // 0 usedoptions.minimumintegerdigits; // 1 usedoptions.pluralcategories; // array [ "one", "other" ] usedoptions.type; // "cardinal" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules.prototype.resolvedoptions' in that specification.
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
the intl.relativetimeformat.prototype.formattoparts() method returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
... 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.
Map.prototype.delete() - JavaScript
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.
Number.prototype.toFixed() - JavaScript
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.
...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.toString() - JavaScript
(it does not inherit object.prototype.tostring()).
...ng()) // displays '17' console.log((17.2).tostring()) // displays '17.2' let x = 6 console.log(x.tostring(2)) // displays '110' console.log((254).tostring(16)) // displays 'fe' console.log((-10).tostring(2)) // displays '-1010' console.log((-0xff).tostring(2)) // displays '-11111111' specifications specification ecmascript (ecma-262)the definition of 'number.prototype.tostring' in that specification.
Object.prototype.__lookupGetter__() - JavaScript
it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof().
...'foo' : 'bar'; }) specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__lookupgetter__()' in that specification.
Object.prototype.toLocaleString() - JavaScript
objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype.tolocalestring() examples array tolocalestring() override on array objects, tolocalestring() can be used to print array values as a string, optionally with locale-specific identifiers (such as currency symbols) appended...
...with the correct separators: for example: const testnumber = 2901234564; // "2901234564" let denumber = testnumber.tolocalestring('de'); // "2.901.234.564" let frnumber = testnumber.tolocalestring('fr'); // "2 901 234 564" specifications specification ecmascript (ecma-262)the definition of 'object.prototype.tolocalestring' in that specification.
RegExp.prototype.dotAll - JavaScript
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.
....log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar // example foo example specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.dotall' in that specification.
RegExp.prototype.flags - JavaScript
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.
... polyfill if (regexp.prototype.flags === undefined) { object.defineproperty(regexp.prototype, 'flags', { configurable: true, get: function() { return this.tostring().match(/[gimsuy]*$/)[0]; } }); } examples using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.flags' in that specification.
RegExp.prototype.global - JavaScript
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.
...using global var regex = new regexp('foo', 'g'); console.log(regex.global); // true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 = new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.global' in that specification.
RegExp.prototype.ignoreCase - JavaScript
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.
... examples using ignorecase var regex = new regexp('foo', 'i'); console.log(regex.ignorecase); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.ignorecase' in that specification.
RegExp.prototype.multiline - JavaScript
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.
... examples using multiline var regex = new regexp('foo', 'm'); console.log(regex.multiline); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification.
RegExp.prototype.source - JavaScript
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".
... 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
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.
...= 2; regex.test('..foo'); // false - index 2 is not the beginning of the string var regex2 = /^foo/my; regex2.lastindex = 2; regex2.test('..foo'); // false - index 2 is not the beginning of the string or line regex2.lastindex = 2; regex2.test('.\nfoo'); // true - index 2 is the beginning of a line specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.sticky' in that specification.
RegExp.prototype.toString() - JavaScript
description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring().
... starting with ecmascript 5, an empty regular expression returns the string "/(?:)/" and line terminators such as "\n" are escaped: new regexp().tostring(); // "/(?:)/" new regexp('\n').tostring() === '/\n/'; // true, prior to es5 new regexp('\n').tostring() === '/\\n/'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.tostring' in that specification.
RegExp.prototype.unicode - JavaScript
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.
... 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.
String.prototype.endsWith() - JavaScript
however, you can polyfill string.prototype.endswith() with the following snippet: if (!string.prototype.endswith) { string.prototype.endswith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; } examples using endswith() let str = 'to be, or not to be, that is the question.' console.log(s...
...tr.endswith('question.')) // true console.log(str.endswith('to be')) // false console.log(str.endswith('to be', 19)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.endswith' in that specification.
String.prototype.includes() - JavaScript
however, you can easily polyfill this method: if (!string.prototype.includes) { string.prototype.includes = function(search, start) { 'use strict'; if (search instanceof regexp) { throw typeerror('first argument must not be a regexp'); } if (start === undefined) { start = 0; } return this.indexof(search, start) !== -1; }; } examples using includes() const str = 'to be, or not to be, that is the question.' console.log(str.includ...
...es('to be')) // true console.log(str.includes('question')) // true console.log(str.includes('nonexistent')) // false console.log(str.includes('to be', 1)) // false console.log(str.includes('to be')) // false console.log(str.includes('')) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.includes' in that specification.
String.prototype.indexOf() - JavaScript
note: for the array method, see array.prototype.indexof().
...e sets count to the number of occurrences of the letter e in the string str: const str = 'to be, or not to be, that is the question.' let count = 0 let position = str.indexof('e') while (position !== -1) { count++ position = str.indexof('e', position + 1) } console.log(count) // displays 4 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.indexof' in that specification.
String.prototype.localeCompare() - JavaScript
// a positive value numeric sorting // by default, "2" > "10" console.log("2".localecompare("10")); // 1 // numeric using options: console.log("2".localecompare("10", undefined, {numeric: true})); // -1 // numeric using locales tag: console.log("2".localecompare("10", "en-u-kn-true")); // -1 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.localecompare' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'string.prototype.localecompare' in that specification.
String.prototype.matchAll() - JavaScript
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.
...h(regexp); // array ['test1', 'test2'] using matchall, you can access capture groups easily: let array = [...str.matchall(regexp)]; array[0]; // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] array[1]; // ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4] specifications specification ecmascript (ecma-262)the definition of 'string.prototype.matchall' in that specification.
String.prototype.repeat() - JavaScript
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.
...r += str; count--; } str += str.substring(0, maxcount - str.length); return str; } } examples using repeat 'abc'.repeat(-1) // rangeerror 'abc'.repeat(0) // '' 'abc'.repeat(1) // 'abc' 'abc'.repeat(2) // 'abcabc' 'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0) // rangeerror ({ tostring: () => 'abc', repeat: string.prototype.repeat }).repeat(2) // 'abcabc' (repeat() is a generic method) specifications specification ecmascript (ecma-262)the definition of 'string.prototype.repeat' in that specification.
String.prototype.search() - JavaScript
(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).
...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.startsWith() - JavaScript
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 ?
... 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
to use this feature in jscript, you can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {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 ?
... this.length + start : start, length) } }(string.prototype.substr); } examples using substr() var astring = 'mozilla'; console.log(astring.substr(0, 1)); // 'm' console.log(astring.substr(1, 0)); // '' console.log(astring.substr(-1, 1)); // 'a' console.log(astring.substr(1, -1)); // '' console.log(astring.substr(-3)); // 'lla' console.log(astring.substr(1)); // 'ozilla' console.log(astring.substr(-20, 2)); // 'mo' console.log(astring.substr(20, 2)); // '' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.substr' in that specification.
String.prototype.substring() - JavaScript
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.toLocaleLowerCase() - JavaScript
ng tolocalelowercase() 'alphabet'.tolocalelowercase(); // 'alphabet' '\u0130'.tolocalelowercase('tr') === 'i'; // true '\u0130'.tolocalelowercase('en-us') === 'i'; // false let locales = ['tr', 'tr', 'tr-tr', 'tr-u-co-search', 'tr-x-turkish']; '\u0130'.tolocalelowercase(locales) === 'i'; // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolocalelowercase' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'string.prototype.tolocalelowercase' in that specification.
String.prototype.toLocaleUpperCase() - JavaScript
owercase() examples using tolocaleuppercase() 'alphabet'.tolocaleuppercase(); // 'alphabet' 'gesäß'.tolocaleuppercase(); // 'gesÄss' 'i\u0307'.tolocaleuppercase('lt-lt'); // 'i' let locales = ['lt', 'lt', 'lt-lt', 'lt-u-co-phonebk', 'lt-x-lietuva']; 'i\u0307'.tolocaleuppercase(locales); // 'i' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolocaleuppercase' in that specification.
... ecmascript internationalization api (ecma-402)the definition of 'string.prototype.tolocaleuppercase' in that specification.
String.prototype.trim() - JavaScript
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' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trim' in that specification.
String.prototype.trimEnd() - JavaScript
aliasing for consistency with functions like string.prototype.padend the standard method name is trimend.
...in some engines this means: string.prototype.trimright.name === "trimend"; examples using trimend() the following example displays the lowercase string ' foo': var str = ' foo '; console.log(str.length); // 8 str = str.trimend(); console.log(str.length); // 6 console.log(str); // ' foo' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trimend' in that specification.
String.prototype.valueOf() - JavaScript
this value is equivalent to string.prototype.tostring().
... 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.toString() - JavaScript
description the symbol object overrides the tostring method of the object object; it does not inherit object.prototype.tostring().
...th them: symbol('foo') + 'bar' // typeerror: can't convert symbol to string examples using tostring symbol('desc').tostring() // "symbol(desc)" // well-known symbols symbol.iterator.tostring() // "symbol(symbol.iterator) // global symbols symbol.for('foo').tostring() // "symbol(foo)" specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.tostring' in that specification.
TypedArray.prototype.every() - JavaScript
this method has the same algorithm as array.prototype.every().
... new uint8array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false new uint8array([12, 54, 18, 130, 44]).every(elem => elem >= 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.every' in that specification.
TypedArray.prototype.filter() - JavaScript
this method has the same algorithm as array.prototype.filter().
... new uint8array([12, 5, 8, 130, 44]).filter(elem => elem >= 10); // uint8array [ 12, 130, 44 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.filter' in that specification.
TypedArray.prototype.findIndex() - JavaScript
polyfill typedarray.prototype.findindex = array.prototype.findindex = array.prototype.findindex || function(evaluator, thisarg) { 'use strict'; if (!this) { throw new typeerror('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function ...
....sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 6, 8, 12]); var uint16 = new uint16array([4, 6, 7, 12]); console.log(uint8.findindex(isprime)); // -1, not found console.log(uint16.findindex(isprime)); // 2 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.findindex' in that specification.
TypedArray.prototype.forEach() - JavaScript
this method has the same algorithm as array.prototype.foreach().
...a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.foreach' in that specification.
TypedArray.prototype.includes() - JavaScript
this method has the same algorithm as array.prototype.includes().
... false uint8.includes(3, 3); // false // nan handling (only true for float32 and float64) new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0 new float32array([nan]).includes(nan); // true; new float64array([nan]).includes(nan); // true; specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.includes' in that specification.
TypedArray.prototype.indexOf() - JavaScript
this method has the same algorithm as array.prototype.indexof().
... examples using indexof var uint8 = new uint8array([2, 5, 9]); uint8.indexof(2); // 0 uint8.indexof(7); // -1 uint8.indexof(9, 2); // 2 uint8.indexof(2, -1); // -1 uint8.indexof(2, -3); // 0 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.indexof' in that specification.
TypedArray.prototype.lastIndexOf() - JavaScript
this method has the same algorithm as array.prototype.lastindexof().
... 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
this method has the same algorithm as array.prototype.map().
... const numbers = new uint8array([1, 4, 9]); const doubles = numbers.map(function(num) { return num * 2; }); // doubles is now uint8array [2, 8, 18] // numbers is still uint8array [1, 4, 9] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.map' in that specification.
TypedArray.prototype.reduceRight() - JavaScript
this method has the same algorithm as array.prototype.reduceright().
... examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduceright' in that specification.
TypedArray.prototype.reverse() - JavaScript
this method has the same algorithm as array.prototype.reverse().
... examples using reverse var uint8 = new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification.
TypedArray.prototype.toLocaleString() - JavaScript
this method has the same algorithm as array.prototype.tolocalestring() and, as the typed array elements are numbers, the same algorithm as number.prototype.tolocalestring() applies for each element.
...nt32array([2000, 500, 8123, 12, 4212]); uint.tolocalestring(); // if run in a de-de locale // "2.000,500,8.123,12,4.212" uint.tolocalestring('en-us'); // "2,000,500,8,123,12,4,212" uint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' }); // "ï¿¥2,000,ï¿¥500,ï¿¥8,123,ï¿¥12,ï¿¥4,212" specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.tolocalestring' in that specification.
TypedArray.prototype.toString() - JavaScript
this method has the same algorithm as array.prototype.tostring().
... 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
the get() prototype method of the webassembly.table() object retrieves a function reference stored at a given index.
... exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown.
TextDecoder.prototype.decode() - Web APIs
the textdecoder.prototype.decode() method returns a domstring containing the text, given in parameters, decoded with the specific method for that textdecoder object.
TextDecoder.prototype.encoding - Web APIs
the textdecoder.prototype.encoding read-only property returns a domstring containing the name of the decoding algorithm used by the specific decoder.
Array.prototype.concat() - JavaScript
ates nested arrays and demonstrates retention of references: const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.concat' in that specification.
Array.prototype.entries() - JavaScript
nd element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.entries' in that specification.
Array.prototype.flat() - JavaScript
[3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] flattening and array holes the flat method removes empty slots in arrays: const arr5 = [1, 2, , 4, 5]; arr5.flat(); // [1, 2, 4, 5] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.flat' in that specification.
Array.prototype.keys() - JavaScript
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
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.
Array.prototype.reverse() - JavaScript
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
specifications specification ecmascript (ecma-262)the definition of 'array.prototype.sort' in that specification.
Array.prototype.splice() - JavaScript
let removed = myfish.splice(-2, 1) // myfish is ["angel", "clown", "sturgeon"] // removed is ["mandarin"] remove all elements from index 2 let myfish = ['angel', 'clown', 'mandarin', 'sturgeon'] let removed = myfish.splice(2) // myfish is ["angel", "clown"] // removed is ["mandarin", "sturgeon"] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.splice' in that specification.
Array.prototype.unshift() - JavaScript
, 2] arr.unshift(-2, -1) // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]) // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]) // the new array length is 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.unshift' in that specification.
ArrayBuffer.prototype.byteLength - JavaScript
examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification.
ArrayBuffer.prototype.slice() - JavaScript
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
examples using valueof typeof object(1n); // object typeof object(1n).valueof(); // bigint specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.valueof()' in that specification.
Boolean.prototype.valueOf() - JavaScript
examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification.
DataView.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification.
DataView.prototype.byteLength - JavaScript
dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.bytelength' in that specification.
DataView.prototype.byteOffset - JavaScript
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
examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification.
DataView.prototype.getBigUint64() - JavaScript
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
examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification.
DataView.prototype.getFloat64() - JavaScript
examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification.
DataView.prototype.getInt16() - JavaScript
examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification.
DataView.prototype.getInt32() - JavaScript
examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification.
DataView.prototype.getInt8() - JavaScript
examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification.
DataView.prototype.getUint16() - JavaScript
examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification.
DataView.prototype.getUint32() - JavaScript
examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification.
DataView.prototype.getUint8() - JavaScript
examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification.
DataView.prototype.setBigInt64() - JavaScript
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
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
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
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
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
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
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
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
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
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
time)" testdate[symbol.toprimitive]('string'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('number'); // returns "1590757517834" testdate[symbol.toprimitive]('default'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.@@toprimitive' in that specification.
Date.prototype.getDate() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var day = xmas95.getdate(); console.log(day); // 25 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getdate' in that specification.
Date.prototype.getFullYear() - JavaScript
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
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
examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification.
Date.prototype.getMinutes() - JavaScript
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
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
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
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
.gettimezoneoffset() / 60; // 1 // get timezone offset for international labour day (may 1) in 2016 // be careful, the date() constructor uses 0-indexed months, so may is // represented with 4 (and not 5) let labourday = new date(2016, 4, 1) let labourdayoffset = labourday.gettimezoneoffset() / 60; specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gettimezoneoffset' in that specification.
Date.prototype.getUTCDate() - JavaScript
var today = new date(); var day = today.getutcdate(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcdate' in that specification.
Date.prototype.getUTCDay() - JavaScript
var today = new date(); var weekday = today.getutcday(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcday' in that specification.
Date.prototype.getUTCFullYear() - JavaScript
var today = new date(); var year = today.getutcfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcfullyear' in that specification.
Date.prototype.getUTCHours() - JavaScript
var today = new date(); var hours = today.getutchours(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutchours' in that specification.
Date.prototype.getUTCMilliseconds() - JavaScript
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
var today = new date(); var minutes = today.getutcminutes(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcminutes' in that specification.
Date.prototype.getUTCMonth() - JavaScript
var today = new date(); var month = today.getutcmonth(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmonth' in that specification.
Date.prototype.getUTCSeconds() - JavaScript
var today = new date(); var seconds = today.getutcseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcseconds' in that specification.
Date.prototype.getYear() - JavaScript
var xmas = new date('december 25, 2015 23:15:00'); xmas.setyear(95); var year = xmas.getyear(); // returns 95 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getyear' in that specification.
Date.prototype.setDate() - JavaScript
y 1962) thebigday.setdate(32); // 1962-08-01 (1st of august 1962) thebigday.setdate(22); // 1962-08-22 (22th of august 1962) thebigday.setdate(0); // 1962-07-31 (31th of july 1962) thebigday.setdate(98); // 1962-10-06 (6th of october 1962) thebigday.setdate(-50); // 1962-08-11 (11th of august 1962) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setdate' in that specification.
Date.prototype.setFullYear() - JavaScript
examples using setfullyear() var thebigday = new date(); thebigday.setfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setfullyear' in that specification.
Date.prototype.setHours() - JavaScript
examples using sethours() var thebigday = new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification.
Date.prototype.setMilliseconds() - JavaScript
examples using setmilliseconds() var thebigday = new date(); thebigday.setmilliseconds(100); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmilliseconds' in that specification.
Date.prototype.setMinutes() - JavaScript
examples using setminutes() var thebigday = new date(); thebigday.setminutes(45); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setminutes' in that specification.
Date.prototype.setMonth() - JavaScript
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
examples using setseconds() var thebigday = new date(); thebigday.setseconds(30); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setseconds' in that specification.
Date.prototype.setTime() - JavaScript
examples using settime() var thebigday = new date('july 1, 1999'); var sameasbigday = new date(); sameasbigday.settime(thebigday.gettime()); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.settime' in that specification.
Date.prototype.setUTCDate() - JavaScript
examples using setutcdate() var thebigday = new date(); thebigday.setutcdate(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcdate' in that specification.
Date.prototype.setUTCFullYear() - JavaScript
examples using setutcfullyear() var thebigday = new date(); thebigday.setutcfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcfullyear' in that specification.
Date.prototype.setUTCHours() - JavaScript
examples using setutchours() var thebigday = new date(); thebigday.setutchours(8); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutchours' in that specification.
Date.prototype.setUTCMilliseconds() - JavaScript
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
examples using setutcminutes() var thebigday = new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification.
Date.prototype.setUTCMonth() - JavaScript
examples using setutcmonth() var thebigday = new date(); thebigday.setutcmonth(11); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmonth' in that specification.
Date.prototype.setUTCSeconds() - JavaScript
examples using setutcseconds() var thebigday = new date(); thebigday.setutcseconds(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcseconds' in that specification.
Date.prototype.setYear() - JavaScript
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
specifications specification ecmascript (ecma-262)the definition of 'date.prototype.todatestring' in that specification.
Date.prototype.toGMTString() - JavaScript
use toutcstring() console.log(str); // mon, 18 dec 1995 17:28:35 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.togmtstring' in that specification.
Date.prototype.toJSON() - JavaScript
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.toTimeString() - JavaScript
examples a basic usage of totimestring() var d = new date(1993, 6, 28, 14, 39, 7); console.log(d.tostring()); // wed jul 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.totimestring()); // 14:39:07 gmt-0600 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.totimestring' in that specification.
Date.prototype.toUTCString() - JavaScript
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.
FinalizationRegistry.prototype.register() - JavaScript
gister(target, "some value", target); the following registers the target object referenced by target, passing in another object as the held value, and not passing in any unregistration token (which means target can't be unregistered): registry.register(target, {"useful": "info about target"}); specifications specification weakrefsthe definition of 'finalizationregistry.prototype.register' in that specification.
FinalizationRegistry.prototype.unregister() - JavaScript
*/ 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
'use strict'; var sdata = 'wisen'; function display() { console.log('sdata value is %s ', this.sdata); } display.call(); // cannot read the property of 'sdata' of undefined specifications specification ecmascript (ecma-262)the definition of 'function.prototype.call' in that specification.
Generator.prototype.next() - JavaScript
function* gen() { while (true) { let value = yield null; console.log(value); } } const g = gen(); g.next(1); // "{ value: null, done: false }" g.next(2); // 2 // "{ value: null, done: false }" specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.next' in that specification.
Generator.prototype.return() - JavaScript
; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.return(); // { value: undefined, done: true } g.return(1); // { value: 1, done: true } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.return' in that specification.
Generator.prototype.throw() - JavaScript
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.DisplayNames.prototype.resolvedOptions() - JavaScript
the intl.displaynames.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current displaynames object.
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
the intl.listformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current listformat object.
Intl.Locale.prototype.baseName - JavaScript
the intl.locale.prototype.basename property returns a substring of the locale's string representation, containing core information about the locale.
Intl.Locale.prototype.calendar - JavaScript
the intl.locale.prototype.calendar property is an accessor property which returns the type of calendar used in the locale.
Intl.Locale.prototype.caseFirst - JavaScript
the intl.locale.prototype.casefirst property is an accessor property that returns whether case is taken into account for the locale's collation rules.
Intl.Locale.prototype.collation - JavaScript
the intl.locale.prototype.collation property is an accessor property that returns the collation type for the locale, which is used to order strings according to the locale's rules.
Intl.Locale.prototype.hourCycle - JavaScript
the intl.locale.prototype.hourcycle property is an accessor property that returns the time keeping format convention used by the locale.
Intl.Locale.prototype.language - JavaScript
the intl.locale.prototype.language property is an accessor property that returns the language associated with the locale.
Intl.Locale.prototype.maximize() - JavaScript
the intl.locale.prototype.maximize() method gets the most likely values for the language, script, and region of the locale based on existing values.
Intl.Locale.prototype.minimize() - JavaScript
the intl.locale.prototype.minimize() method attempts to remove information about the locale that would be added by calling locale.maximize().
Intl.Locale.prototype.numberingSystem - JavaScript
the intl.locale.prototype.numberingsystem property is an accessor property that returns the numeral system used by the locale.
Intl.Locale.prototype.numeric - JavaScript
the intl.locale.prototype.numeric property is an accessor property that returns whether the locale has special collation handling for numeric characters.
Intl.Locale.prototype.region - JavaScript
the intl.locale.prototype.region property is an accessor property that returns the region of the world (usually a country) associated with the locale.
Intl.Locale.prototype.script - JavaScript
the intl.locale.prototype.script property is an accessor property which returns the script used for writing the particular language used in the locale.
Intl.Locale.prototype.toString() - JavaScript
the intl.locale.prototype.tostring() returns the locale's full locale identifier string.
Intl.RelativeTimeFormat.prototype.format() - JavaScript
the intl.relativetimeformat.prototype.format() method formats a value and unit according to the locale and formatting options of this relativetimeformat object.
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.relativetimeformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this relativetimeformat object.
Map.prototype[@@iterator]() - JavaScript
h for..of const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') for (const entry of mymap) { console.log(entry) } // ["0", "foo"] // [1, "bar"] // [{}, "baz"] for (const [key, value] of mymap) { console.log(`${key}: ${value}`) } // 0: foo // 1: bar // [object]: baz specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@iterator]()' in that specification.
Map.prototype[@@toStringTag] - JavaScript
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
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.entries() - JavaScript
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
element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.foreach' in that specification.
Map.prototype.get() - JavaScript
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
examples using has() let mymap = new map() mymap.set('bar', "foo") mymap.has('bar') // returns true mymap.has('baz') // returns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification.
Map.prototype.keys() - JavaScript
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
mymap.set('bar', 'foo') .set(1, 'foobar') .set(2, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'map.prototype.set' in that specification.
Map.prototype.size - JavaScript
examples using size var mymap = new map(); mymap.set('a', 'alpha'); mymap.set('b', 'beta'); mymap.set('g', 'gamma'); mymap.size // 3 specifications specification ecmascript (ecma-262)the definition of 'map.prototype.size' in that specification.
Map.prototype.values() - JavaScript
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
l var numobj = 77.1234; console.log(numobj.toexponential()); // logs 7.71234e+1 console.log(numobj.toexponential(4)); // logs 7.7123e+1 console.log(numobj.toexponential(2)); // logs 7.71e+1 console.log(77.1234.toexponential()); // logs 7.71234e+1 console.log(77 .toexponential()); // logs 7.7e+1 specifications specification ecmascript (ecma-262)the definition of 'number.prototype.toexponential' in that specification.
Number.prototype.valueOf() - JavaScript
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
o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { return 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmefive', { get: function() { return 5; } }); console.log(o.gimmefive); // 5 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__definegetter__()' in that specification.
Object.prototype.__defineSetter__() - JavaScript
.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'value', { set: function(val) { this.anothervalue = val; } }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__definesetter__()' in that specification.
Object.prototype.__lookupSetter__() - JavaScript
operty setter var obj = { set foo(value) { this.bar = value; } }; // non-standard and deprecated way obj.__lookupsetter__('foo') // (function(value) { this.bar = value; }) // standard-compliant way object.getownpropertydescriptor(obj, 'foo').set; // (function(value) { this.bar = value; }) specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__lookupsetter__()' in that specification.
Promise.prototype.finally() - JavaScript
for more details, refer to: 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 'promise.prototype.finally' in that specification.
RegExp.prototype.compile() - JavaScript
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.
Set.prototype[@@iterator]() - JavaScript
yset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); for (const v of myset) { console.log(v); } specifications specification ecmascript (ecma-262)the definition of 'set.prototype[@@iterator]' in that specification.
Set.prototype.add() - JavaScript
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
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
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
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
ct the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach' in that specification.
Set.prototype.has() - JavaScript
as('foo'); // returns true myset.has('bar'); // returns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications specification ecmascript (ecma-262)the definition of 'set.prototype.has' in that specification.
Set.prototype.size - JavaScript
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
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
examples using bytelength var sab = new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification.
String.prototype[@@iterator]() - JavaScript
console.log(striter.next().value); // "a" console.log(striter.next().value); // "\ud835\udc68" using [@@iterator]() with for..of var str = 'a\ud835\udc68b\ud835\udc69c\ud835\udc6a'; for (var v of str) { console.log(v); } // "a" // "\ud835\udc68" // "b" // "\ud835\udc69" // "c" // "\ud835\udc6a" specifications specification ecmascript (ecma-262)the definition of 'string.prototype[@@iterator]()' in that specification.
String.prototype.anchor() - JavaScript
examples using anchor() var mystring = 'table of contents'; document.body.innerhtml = mystring.anchor('contents_anchor'); will output the following html: <a name="contents_anchor">table of contents</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.anchor' in that specification.
String.prototype.big() - JavaScript
ig()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <fontsize=7>hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '2em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.big' in that specification.
String.prototype.blink() - JavaScript
of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.blink' in that specification.
String.prototype.bold() - JavaScript
of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.bold' in that specification.
String.prototype.charAt() - JavaScript
} } if (idx >= end || idx < 0) { return '' } ret += str.charat(idx) if (/[\ud800-\udbff]/.test(ret) && /[\udc00-\udfff]/.test(str.charat(idx + 1))) { // go one further, since one of the "characters" is part of a surrogate pair ret += str.charat(idx + 1) } return ret } specifications specification ecmascript (ecma-262)the definition of 'string.prototype.charat' in that specification.
String.prototype.charCodeAt() - JavaScript
charcodeat(idx); var hi, low; if (0xd800 <= code && code <= 0xdbff) { hi = code; low = str.charcodeat(idx + 1); // go one further, since one of the "characters" // is part of a surrogate pair return ((hi - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000; } return code; } specifications specification ecmascript (ecma-262)the definition of 'string.prototype.charcodeat' in that specification.
String.prototype.concat() - JavaScript
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
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
' is red in hexadecimal in this line'); // '<font color="ff00">hello, world</font> is red in hexadecimal in this line' with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.color = 'red'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontcolor' in that specification.
String.prototype.fontsize() - JavaScript
; // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontsize' in that specification.
String.prototype.italics() - JavaScript
ing of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.italics' in that specification.
String.prototype.lastIndexOf() - JavaScript
); // logs 8 console.log('the index of the first w from the end is ' + anystring.lastindexof('w')); // logs 10 console.log('the index of "new" from the beginning is ' + anystring.indexof('new')); // logs 6 console.log('the index of "new" from the end is ' + anystring.lastindexof('new')); // logs 6 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.lastindexof' in that specification.
String.prototype.link() - JavaScript
var hottext = 'mdn'; var url = 'https://developer.mozilla.org/'; console.log('click to return to ' + hottext.link(url)); // click to return to <a href="https://developer.mozilla.org/">mdn</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.link' in that specification.
String.prototype.normalize() - JavaScript
ompatibly-composed (nfkc) // u+1e69: latin small letter s with dot below and dot above str.normalize('nfkc'); // '\u1e69' // compatibly-decomposed (nfkd) // u+0073: latin small letter s // u+0323: combining dot below // u+0307: combining dot above str.normalize('nfkd'); // '\u0073\u0323\u0307' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.normalize' in that specification.
String.prototype.padEnd() - JavaScript
examples using padend 'abc'.padend(10); // "abc " 'abc'.padend(10, "foo"); // "abcfoofoof" 'abc'.padend(6, "123456"); // "abc123" 'abc'.padend(1); // "abc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padend' in that specification.
String.prototype.padStart() - JavaScript
// "abc" fixed width string number conversion // javascript version of: (unsigned) // printf "%0*d" width num function leftfillnum(num, targetlength) { return num.tostring().padstart(targetlength, 0); } const num = 123; console.log(leftfillnum(num, 5)); // expected output: "00123" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padstart' in that specification.
String.prototype.replace() - JavaScript
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
this won't work: 'aabbcc'.replaceall(/b/, '.'); typeerror: replaceall must be called with a global regexp this will work: 'aabbcc'.replaceall(/b/g, '.'); "aa..cc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.replaceall' in that specification.
String.prototype.slice() - JavaScript
console.log(str.slice(-5, -1)) // => "n us" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.slice' in that specification.
String.prototype.small() - JavaScript
; // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.small' in that specification.
String.prototype.split() - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'string.prototype.split' in that specification.
String.prototype.strike() - JavaScript
tting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.strike' in that specification.
String.prototype.sub() - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sub' in that specification.
String.prototype.sup() - JavaScript
: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // "this is what a <sup>superscript</sup> looks like." console.log('this is what a ' + subtext.sub() + ' looks like.'); // "this is what a <sub>subscript</sub> looks like." specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sup' in that specification.
String.prototype.toLowerCase() - JavaScript
examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification.
Symbol.prototype[@@toPrimitive] - JavaScript
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
examples using valueof const sym = symbol("example"); sym === sym.valueof(); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.valueof' in that specification.
TypedArray.prototype[@@iterator]() - JavaScript
alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype[@@iterator]()' in that specification.
TypedArray.prototype.buffer - JavaScript
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
(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.bytelength; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.bytelength' in that specification.
TypedArray.prototype.byteOffset - JavaScript
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
on var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, 20] console.log(earr.next().value); // [2, 30] console.log(earr.next().value); // [3, 40] console.log(earr.next().value); // [4, 50] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.entries()' in that specification.
TypedArray.prototype.find() - JavaScript
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
nsole.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().value); // 2 console.log(earr.next().value); // 3 console.log(earr.next().value); // 4 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.keys()' in that specification.
TypedArray.prototype.length - JavaScript
= new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.length' in that specification.
TypedArray.prototype.set() - JavaScript
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
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
og(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.values()' in that specification.
WeakMap.prototype.delete() - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.delete' in that specification.
WeakMap.prototype.get() - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.get' in that specification.
WeakMap.prototype.has() - JavaScript
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
examples using the set method var wm = new weakmap(); var obj = {}; // add new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification.
WeakRef.prototype.deref() - JavaScript
tick = () => { // get the element from the weak reference, if it still exists const element = this.ref.deref(); if (element) { element.textcontent = ++this.count; } else { // the element doesn't exist anymore console.log("the element is gone."); this.stop(); this.ref = null; } }; specifications specification weakrefsthe definition of 'weakref.prototype.deref()' in that specification.
WeakSet.prototype.add() - JavaScript
les using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); // true // weakset only takes objects as arguments ws.add(1); // results in "typeerror: invalid value used in weak set" in chrome // and "typeerror: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.add' in that specification.
WeakSet.prototype.delete() - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.delete' in that specification.
WeakSet.prototype.has() - JavaScript
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
the exports readonly property of the webassembly.instance object prototype 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.
WebAssembly.Memory.prototype.buffer - JavaScript
the buffer prototype property of the webassembly.memory object returns the buffer contained in the memory.
WebAssembly.Table.prototype.grow() - JavaScript
the grow() prototype method of the webassembly.table object increases the size of the table instance by a specified number of elements.
WebAssembly.Table.prototype.length - JavaScript
the length prototype property of the webassembly.table object returns the length of the table, i.e.
Details of the object model - JavaScript
« previousnext » javascript is an object-based language based on prototypes, rather than being class-based.
...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 prototype-based language, such as javascript, does not make this distinction: it simply has objects.
...And 59 more matches
TypedArray - JavaScript
description ecmascript 2015 defines a typedarray constructor that serves as the [[prototype]] of all typedarray constructors.
... it is only directly accessible through object.getprototypeof(int8array) and similar.
... additionally, all typed array prototypes (typedarray.prototype) have %typedarray%.prototype as their [[prototype]].
...And 57 more matches
BigInt64Array - JavaScript
instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array.
... bigint64array.prototype.bytelength returns the length (in bytes) of the bigint64array from the start of its arraybuffer.
... bigint64array.prototype.byteoffset returns the offset (in bytes) of the bigint64array from the start of its arraybuffer.
...And 50 more matches
BigUint64Array - JavaScript
instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array.
... biguint64array.prototype.bytelength returns the length (in bytes) of the biguint64array from the start of its arraybuffer.
... biguint64array.prototype.byteoffset returns the offset (in bytes) of the biguint64array from the start of its arraybuffer.
...And 50 more matches
Float32Array - JavaScript
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.
... float32array.prototype.byteoffset returns the offset (in bytes) of the float32array from the start of its arraybuffer.
...And 50 more matches
Float64Array - JavaScript
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.
... float64array.prototype.byteoffset returns the offset (in bytes) of the float64array from the start of its arraybuffer.
...And 50 more matches
Int16Array - JavaScript
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.
... int16array.prototype.byteoffset returns the offset (in bytes) of the int16array from the start of its arraybuffer.
...And 50 more matches
Int32Array - JavaScript
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.
... int32array.prototype.byteoffset returns the offset (in bytes) of the int32array from the start of its arraybuffer.
...And 50 more matches
Int8Array - JavaScript
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.
... int8array.prototype.byteoffset returns the offset (in bytes) of the int8array from the start of its arraybuffer.
...And 50 more matches
Uint16Array - JavaScript
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.
... uint16array.prototype.byteoffset returns the offset (in bytes) of the uint16array from the start of its arraybuffer.
...And 50 more matches
Uint32Array - JavaScript
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.
... uint32array.prototype.byteoffset returns the offset (in bytes) of the uint32array from the start of its arraybuffer.
...And 50 more matches
Uint8Array - JavaScript
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.
... uint8array.prototype.byteoffset returns the offset (in bytes) of the uint8array from the start of its arraybuffer.
...And 50 more matches
Uint8ClampedArray - JavaScript
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.
... uint8clampedarray.prototype.byteoffset returns the offset (in bytes) of the uint8clampedarray from the start of its arraybuffer.
...And 50 more matches
Date - JavaScript
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.
...And 48 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...
...rmat(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 = 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 = function sethsl(hue, saturation, lightness) { this.hue = hue; this.saturation = saturation; this.lightness = lightness; this.hsltorgb(); }; color.prototype.sethue = function sethue(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 359) return; this.hue = value; this.updatergb(); }; color.prototype.setsaturation = function setsaturation(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 100...
...And 42 more matches
Index
64 js::protokeytoid jsapi reference, reference, référence(2), spidermonkey js::protokeytoid converts a specified js prototype key key, to a js id.
...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.
... 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.
...And 37 more matches
String - JavaScript
instance properties string.prototype.length reflects the length of the string.
... 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 34 more matches
Classes and Inheritance - Archive of obsolete content
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.
...And 32 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...
...rmat(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 = 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 = function sethsl(hue, saturation, lightness) { this.hue = hue; this.saturation = saturation; this.lightness = lightness; this.hsltorgb(); }; color.prototype.sethue = function sethue(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 359) return; this.hue = value; this.updatergb(); }; color.prototype.setsaturation = function setsaturation(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 100...
...And 32 more matches
Array - JavaScript
description arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.
... instance properties array.prototype.length reflects the number of elements in an array.
... array.prototype[@@unscopables] a symbol containing property names to exclude from a with binding scope.
...And 32 more matches
Object - JavaScript
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.
...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.
...And 30 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 = 0; daemon.prototype.onstart = null; daemon.prototype.onstop = null; /* these properties should be read-only after the creation of the daemon */ daemon.prototype.session = -1; daemon.prototype.index = 0; daemon.prototype.paused = true; daemon.prototype.backw = true; /* system required daemon global object methods */ daemon.forcecall = function (odmn) { odmn.index += odmn.backw ?
...calling daemon.incorporate(@func) will modify the @func.prototype property!
...And 23 more matches
Inheritance in JavaScript - Learn web development
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.
...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!
...And 22 more matches
DataView - JavaScript
instance properties dataview.prototype.buffer the arraybuffer referenced by this view.
... dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer.
... dataview.prototype.byteoffset the offset (in bytes) of this view from the start of its arraybuffer.
...And 20 more matches
JS_InitClass
make a jsclass accessible to javascript code by creating its prototype, constructor, properties, and functions.
... 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.
...And 17 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.
... 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.
...And 17 more matches
RegExp - JavaScript
instance properties regexp.prototype.flags a string that contains the flags of the regexp object.
... regexp.prototype.dotall whether .
... regexp.prototype.global whether to test the regular expression against all possible matches in a string, or only against the first.
...And 16 more matches
core/heritage - Archive of obsolete content
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.
...dog.prototype.type = 'dog'; dog.prototype.bark = function bark() { return 'ruff!
... ruff!' }; // subclassing a `dog` function pet(name, breed) { // once again we do our little dance if (!(this instanceof pet)) return new pet(name, breed); dog.call(this, name); this.breed = breed; } // to subclass, you need to make another special dance with special // 'prototype' properties.
...And 15 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 |...
... 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; c = (c + m) * precision; x = (x + m) * precision; m = m * precision; if (h >= 0 && h < 1) { th...
...is.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; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cm...
...And 15 more matches
Bytecode Descriptions
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.
...this is used to define the .prototype property on classes.
...And 13 more matches
JS_NewObject
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.
...And 13 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
javascript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and es2015 classes).
... 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).
... for more on objects and prototypes see object.prototype.
...And 13 more matches
Symbol - JavaScript
used by array.prototype.concat().
...used by string.prototype.match().
...used by string.prototype.matchall().
...And 13 more matches
Property cache
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.
...(informally: objects with the same shape have the same prototype, class, and layout.) prototype chain shadowing guarantee — if at t0 the object x has shape s and a property x.p of x is found along the prototype chain on object x' of shape s', where x !== x', and the lookup called no resolve hooks or non-native lookup ops, and at t1 the object x has shape s, the object x' has shape s', and no shape-regenerating gc occurred, then at t1 the lookup for x.p still finds the same pr...
...And 12 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...
...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) ?
...And 10 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...
...is,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(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","sli...
...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
Debugger.Object - Firefox Developer Tools
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.
... 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.
... accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent's prototype (as a new debugger.object instance), or null if it has no prototype.
...And 10 more matches
Intl.Locale - JavaScript
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.
...And 10 more matches
Map - JavaScript
an object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.
... 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 10 more matches
SourceMap.jsm
sourcemapconsumer.prototype.originalpositionfor(generatedposition) returns the original source, line, and column information for the generated source's line and column positions provided.
... 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.
... sourcemapgenerator.prototype.tostring() renders the source map being generated to a string.
...And 8 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 aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
...*/) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ?
...And 8 more matches
Working with objects - JavaScript
to illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function: function showprops(obj, objname) { var result = ``; for (var i in obj) { // obj.hasownproperty() is used to filter out properties from the object's prototype chain if (obj.hasownproperty(i)) { result += `${objname}.${i} = ${obj[i]}\n`; } } return result; } so, the function call showprops(mycar, "mycar") would 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 l...
...oops 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.
...And 8 more matches
Error - JavaScript
instance properties error.prototype.message error message.
... error.prototype.name error name.
... error.prototype.description a non-standard microsoft property for the error description.
...And 8 more matches
Set - JavaScript
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.
... set.prototype.clear() removes all elements from the set object.
...And 8 more matches
Index - Archive of obsolete content
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.
...see also the newer version of date.prototype.tolocaledatestring().
... 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.
...And 7 more matches
Xray vision
for example, if content code creates a new date object, it will usually be created as a property of a dom object, and then it will be filtered out by the dom xray: // content code // redefine date.getfullyear() date.prototype.getfullyear = function() {return 1000}; var date = new date(); // chrome code // contentwindow is an xray, and date is an expando on contentwindow // so date is filtered out gbrowser.contentwindow.date.getfullyear() // -> typeerror: gbrowser.contentwindow.date is undefined the chrome code will only even see date if it waives xrays, and then, because waiving is transitive, it should expect to b...
... like dom objects, most javascript built-in objects have an underlying c++ state that is separate from their javascript representation, so the xray implementation can go straight to the c++ state and guarantee that the object will behave as its specification defines: // chrome code var sandboxscript = 'date.prototype.getfullyear = function() {return 1000};' + 'var date = new date(); '; var sandbox = components.utils.sandbox("https://example.org/"); components.utils.evalinsandbox(sandboxscript, sandbox); // date objects are xrayed console.log(sandbox.date.getfullyear()); // -> 2014 // but you can waive xray vision console.log(components.utils.waivexrays(sandbox.date).getfullyear()); // -...
... there are two main sorts of restrictions: first, the chrome code might expect to rely on the prototype's integrity, so the object's prototype is protected: the xray has the standard object or array prototype, without any modifications that content may have done to that prototype.
...And 7 more matches
Debugger.Object - Firefox Developer Tools
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.
... 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.
... accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent’s prototype (as a new debugger.object instance), or null if it has no prototype.
...And 7 more matches
Element.classList - Web APIs
WebAPIElementclassList
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.
...string.prototype.trim polyfill if (!"".trim) string.prototype.trim = function(){ return this.replace(/^[\s]+|[\s]+$/g, ''); }; (function(window){"use strict"; // prevent global namespace pollution if(!window.domexception) (domexception = function(reason){this.message = reason}).prototype = new error; var wsre = /[\11\12\14\15\40]/, wsindex = 0, checkifvalidclasslistentry = function(o, v) { if (v === "") throw new domexception( "failed to execute '" + o + "' on 'domtokenlist': the token provided must not be empty." ); if((wsindex=v.search(wsre))!==-1) throw new domexception("failed to execute '"+o+"' on 'domtokenlist': " + "the token provided ('"+v[wsindex]+"') contains html space characters, which are not valid in tokens."); } // 2.
...And 7 more matches
File - Web APIs
WebAPIFile
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.
...And 7 more matches
Index - Web APIs
WebAPIIndex
rsedvalue.entries() api, css typed object model api, cssunparsedvalue, constructor, entries, experimental, houdini, method, needsexample, reference the cssunparsedvalue.entries() method 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).
...utmap.entries api, entries, experimental, keyboard api, keyboard map, keyboardlayoutmap, property, reference, keyboard 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).
... 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.
...And 7 more matches
Number - JavaScript
number.prototype allows the addition of properties to the number object.
... 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.
...And 7 more matches
Old Proxy API - Archive of obsolete content
warning: the spidermonkey proxy implementation is a prototype and the proxy api and semantics specifications are unstable.
...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).
...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.
...And 6 more matches
Rhino scopes and contexts
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.
... order of lookups in a two-deep scope chain with prototypes.
... to do this we set an object's prototype.
...And 6 more matches
WebAssembly.CompileError - JavaScript
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.
...And 6 more matches
WebAssembly.LinkError - JavaScript
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.
...And 6 more matches
WebAssembly.RuntimeError - JavaScript
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.
...And 6 more matches
NSS functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
...the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
...the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
...And 5 more matches
Classes - JavaScript
classes in js are built on prototypes but also have some syntax and semantics that are not shared with es5 classalike semantics.
... prototype methods see also method definitions.
... 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.
...And 5 more matches
RangeError - JavaScript
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().
... 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.
...And 5 more matches
WebIDL bindings
[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.
... [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.
...And 4 more matches
Blob - Web APIs
WebAPIBlob
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.
... instance methods blob.prototype.arraybuffer() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data.
...And 4 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
*/ ) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
...*/ ) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ?
... settimeout.call(myarray, myarray.mymethod, 2.0*1000); // error: "ns_error_xpc_bad_op_on_wn_proto: illegal operation on wrappednative prototype object" settimeout.call(myarray, myarray.mymethod, 2.5*1000, 2); // same error possible solutions a common way to solve the problem is to use a wrapper function that sets this to the required value: settimeout(function(){myarray.mymethod()}, 2.0*1000); // prints "zero,one,two" after 2 seconds settimeout(function(){myarray.mymethod('1')}, 2.5*1000); // prints "one" after 2.5 seconds arrow fun...
...And 4 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.
...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.style.width = this.width + units[this.unitx]; this.updateborderradius(); } radiuscontainer.prototype.setheight = function setheight(value) { this.radius.style.display = 'block'; this.height = 2 * value; this.node.style.height = this.height + units[this.unity]; this.updateborderradius(); } radiuscontainer.prototype.set...
...And 4 more matches
BigInt - JavaScript
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).
...And 4 more matches
EvalError - JavaScript
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.
...And 4 more matches
ReferenceError - JavaScript
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.
...And 4 more matches
SyntaxError - JavaScript
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.
...And 4 more matches
TypeError - JavaScript
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.
...And 4 more matches
URIError - JavaScript
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.
...And 4 more matches
Object initializer - JavaScript
shallow-cloning (excluding prototype) or merging objects is now possible using a shorter syntax than object.assign().
... prototype mutation a property definition of the form __proto__: value or "__proto__": value does not create a property with the name __proto__.
... instead, if the provided value is an object or null, it changes the [[prototype]] of the created object to that value.
...And 4 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.
... constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain.
... // defining constructors function c() {} function d() {} let o = new c() // true, because: object.getprototypeof(o) === c.prototype o instanceof c // false, because d.prototype is nowhere in o's prototype chain o instanceof d o instanceof object // true, because: c.prototype instanceof object // true c.prototype = {} let o2 = new c() o2 instanceof c // true // false, because c.prototype is nowhere in // o's prototype chain anymore o instanceof c d.prototype = new c() // add c to [[prototype]] linkage of d let o3 = new d() o3 instanceof d // true o3 instanceof c // true since c.prototype is now in o3's prototype chain note that the value of an instanceof test can change based on changes to the prototype property of constructors.
...And 4 more matches
for...in - JavaScript
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).
...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.
...And 4 more matches
Using the WebAssembly JavaScript API - WebAssembly
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.
... 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.
...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).
...And 4 more matches
core/namespace - Archive of obsolete content
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); // ...
... 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); // ...
...And 3 more matches
JXON - Archive of obsolete content
jxontree.prototype.valueof = function () { return this.keyvalue; }; jxontree.prototype.tostring = function () { return string(this.keyvalue); }; jxontree.prototype.getitem = function (nitem) { if (nlength === 0) { return null; } var ncount = 0; for (var skey in this) { if (ncount === nitem) { return this[skey]; } ncount++; } return null; }; jxontree.prototype.getattribute = function (nattrid) { if (nattrl...
...en === 0 || nattrid + 1 > nattrlen) { return null; } var nattr = 0; for (var sattrname in this.keyattributes) { if (nattr === nattrid) { return this.keyattributes[sattrname]; } nattr++; } return null; }; jxontree.prototype.haschildren = function () { return this.keylength > 0; }; */ var myobject = new jxontree(doc); // we got our javascript object!
...-standalone.html |*| \*/ const jxon = new (function () { function parsetext (svalue) { if (risnull.test(svalue)) { return null; } if (risbool.test(svalue)) { return svalue.tolowercase() === "true"; } if (isfinite(svalue)) { return parsefloat(svalue); } if (isfinite(date.parse(svalue))) { return new date(svalue); } return svalue; } function emptytree () {} emptytree.prototype.tostring = function () { return "null"; }; emptytree.prototype.valueof = function () { return null; }; function objectify (vval) { return vval === null ?
...And 3 more matches
New in JavaScript 1.3 - Archive of obsolete content
--> new features in javascript 1.3 new globals nan infinity undefined new methods isfinite() function.prototype.call() function.prototype.apply() date.utc() date.prototype.getfullyear() date.prototype.setfullyear() date.prototype.getmilliseconds() date.prototype.setmilliseconds() date.prototype.getutcfullyear() date.prototype.getutcmonth() date.prototype.getutcdate() date.prototype.getutchours() date.prototype.getutcminutes() date.prototype.getutcseconds() date.prototype.getutcmilliseconds() ...
...date.prototype.toutcstring() date.prototype.setutcfullyear() date.prototype.setutcmonth() date.prototype.setutcdate() date.prototype.setutchours() date.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a javascript console was introduced.
... array.prototype.push(): in javascript 1.2, the push method returned the last element added to an array.
...And 3 more matches
Archived JavaScript Reference - Archive of obsolete content
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.
...see also the newer version of date.prototype.tolocaledatestring().ecmascript 2016 to es.next support in mozillaexpression closuresexpression closures are a shorthand function syntax for writing simple functions.for each...inthe for each...in statement iterates a specified variable over all values of object's properties.
... for each distinct property, a specified statement is executed.function.aritynot part of any standard.function.prototype.isgenerator()the non-standard isgenerator() method used to determine whether or not a function is a generator.
...And 3 more matches
Reference - Archive of obsolete content
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 a...
...lert(function.myfunction); //available in function so no matter what we prototype function or object , it will be available in both...
... alert(array.myfunction); //available in array (array cannot be prototyped) object -> function -> instance but there is another but...
...And 3 more matches
Mozilla DOM Hacking Guide
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.
...therefore, the first interface in the prototype chain for the span element is htmlelement.
... when should domclassinfo be used to add a new interface to an existing dom object to expose a new dom object to javascript to add a new js external constructor, like "new image()" to bypass the default behavior of xpconnect to implement a "replaceable" property to mess with the prototypes of dom objects example of functionality implemented using domclassinfo: constructors of dom objects in the global scope (e.g.
...And 3 more matches
nsIXPConnect
tptr ajscontext, out nsixpcsecuritymanager amanager, out pruint16 flags); nsixpconnectwrappednative getwrappednativeofjsobject(in jscontextptr ajscontext, in jsobjectptr ajsobj); nsixpconnectwrappednative getwrappednativeofnativeobject(in jscontextptr ajscontext, in jsobjectptr ascope, in nsisupports acomobj, in nsiidref aiid); nsixpconnectjsobjectholder getwrappednativeprototype(in jscontextptr ajscontext, in jsobjectptr ascope, in nsiclassinfo aclassinfo); jsval getwrapperforobject(in jscontextptr ajscontext, in jsobjectptr aobject, in jsobjectptr ascope, in nsiprincipal aprincipal, in unsigned long afilenameflags); 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!
... proto the (newly created) prototype object for a dom class.
...And 3 more matches
Debugger.Frame - Firefox Developer Tools
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.
...for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame.
... 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.
...And 3 more matches
TextEncoder - Web APIs
textencoder.prototype.encodingread only always returns "utf-8".
... 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.
...And 3 more matches
WebGL model view projection - Web APIs
webglbox.prototype.draw = function(settings) { // create some attribute data; these are the triangles that will end being // drawn to the screen.
...the new function looks like this: cubedemo.prototype.computemodelmatrix = function(now) { //scale down by 50% var scale = mdn.scalematrix(0.5, 0.5, 0.5); // rotate a slight tilt var rotatex = mdn.rotatexmatrix(now * 0.0003); // rotate according to time var rotatey = mdn.rotateymatrix(now * 0.0005); // move slightly down var position = mdn.translatematrix(0, -0.1, 0); // multiply together, make sure and read them in opposite or...
...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.
...And 3 more matches
Using Web Workers - Web APIs
*/ 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.
...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...
...etc): calls a worker's queryable function * postmessage(string or json data): see worker.prototype.postmessage() * terminate(): terminates the worker * addlistener(name, function): adds a listener * removelistener(name): removes a listener queryableworker instances properties: * defaultlistener: the default listener executed only when the worker calls the postmessage() function directly */ function queryableworker(url, defaultlistener, onerror) { ...
...And 3 more matches
Meta programming - JavaScript
handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof 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).
... handler.setprototypeof() object.setprototypeof() reflect.setprototypeof() if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target).
...And 3 more matches
Regular expressions - JavaScript
regexp.prototype.global i case-insensitive search.
... regexp.prototype.ignorecase m multi-line search.
... regexp.prototype.multiline s allows .
...And 3 more matches
InternalError - JavaScript
instance properties internalerror.prototype.message error message.
... internalerror.prototype.name error name.
... internalerror.prototype.filename path to file that raised this error.
...And 3 more matches
Comparing Reflect and Object methods - JavaScript
n/a getprototypeof() object.getprototypeof() returns the prototype of the given object.
... reflect.getprototypeof() returns the prototype of the given object.
... setprototypeof() object.setprototypeof() returns the object itself if its prototype was set successfully.
...And 3 more matches
Reflect.construct() - JavaScript
it gives also the added option to specify a different prototype.
... newtarget optional the constructor whose prototype should be used.
...(this would also be possible by using the spread syntax combined with the new operator.) let obj = new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using object.create().
...And 3 more matches
Spread syntax (...) - JavaScript
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.
...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...
... 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.
...And 3 more matches
delete operator - JavaScript
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).
...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).
...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.
...And 3 more matches
this - JavaScript
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.
... 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().
... 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.
...And 3 more matches
JavaScript Client API - Archive of obsolete content
the skeleton of a sample record implementation: function foorecord(collection, id) { cryptowrapper.call(this, collection, id); } foorecord.prototype = { __proto__: cryptowrapper.prototype, _logname: "record.foo", ttl: foo_ttl, // optional get bar() this.cleartext.bar, set bar(value) { this.cleartext.bar = value; }, get baz() this.cleartext.baz, set baz(value) { this.cleartext.baz = value; } }; to save all that typing for declaring the getters and setters, you can also use utils.defergetset: function foorecord(co...
...llection, id) { cryptowrapper.call(this, collection, id); } foorecord.prototype = { __proto__: cryptowrapper.prototype, _logname: "record.foo", ttl: foo_ttl // optional }; utils.defergetset(foorec, "cleartext", ["bar", "baz"]); the store object the store object (which extends store, as defined in services/sync/modules/engines.js) has the job of creating and maintaining a set of record objects from the underlying data.
...function foostore(name) { store.call(this, name); } foostore.prototype = { __proto__: store.prototype, itemexists: function(guid) { // return true if an item with given guid exists in the store.
...And 2 more matches
ECMAScript 2015 support in Mozilla - Archive of obsolete content
standard library additions to the array object array iteration with for...of (firefox 13) array.from() (firefox 32) array.of() (firefox 25) array.prototype.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firefox 28), array.prototype.values() array.prototype.copywithin() (firefox 32) get array[@@species] (firefox 48) new map and set objects, and their weak counterparts map (firefox 13) map iteration with for...of (firefox 17) map.prototype.f...
...oreach() (firefox 25) map.prototype.entries() (firefox 20) map.prototype.keys() (firefox 20) map.prototype.values() constructor argument: new map(null) (firefox 37) monkey-patched set() in constructor (firefox 37) get map[@@species] (firefox 41) set (firefox 13) set iteration with for...of (firefox 17) set.prototype.foreach() (firefox 25) set.prototype.entries(), set.prototype.keys(), set.prototype.values() (firefox 24) constructor argument: new set(null) (firefox 37) monkey-patched add() in constructor (firefox 37) get set[@@species] (firefox 41) weakmap (firefox 6) weakmap.clear() (firefox 20) optional iterable argument in weakmap constructor (firefox 36) constructor argument: new weakmap(null) (firefox 37) monkey-patched s...
...sign(), math.cbrt() (firefox 25) additions to the number object number.isnan() (firefox 16) number.isfinite() (firefox 16) number.isinteger() (firefox 16) number.parseint() (firefox 25) number.parsefloat() (firefox 25) number.epsilon (firefox 25) number.max_safe_integer, number.min_safe_integer (firefox 31) number.issafeinteger() (firefox 32) additions to the object object object.prototype.__proto__ has been standardized object.is() (firefox 22) object.setprototypeof() (firefox 31) object.assign() (firefox 34) object.getownpropertysymbols() (firefox 33) additions to the date object date.prototype is an ordinary object (firefox 41) generic date.prototype.tostring (firefox 41) date.prototype[@@toprimitive] (firefox 44) new promise object promise (firefox 24, enabled b...
...And 2 more matches
2D maze game with device orientation - Game development
var ball = { _width: 320, _height: 480 }; ball.boot = function(game) {}; ball.boot.prototype = { preload: function() { this.load.image('preloaderbg', 'img/loading-bg.png'); this.load.image('preloaderbar', 'img/loading-bar.png'); }, create: function() { this.game.scale.scalemode = phaser.scalemanager.show_all; this.game.scale.pagealignhorizontally = true; this.game.scale.pagealignvertically = true; this.game.state.start('preloade...
... 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'); // ...
... ball.mainmenu = function(game) {}; ball.mainmenu.prototype = { create: function() { this.add.sprite(0, 0, 'screen-mainmenu'); this.gametitle = this.add.sprite(ball._width*0.5, 40, 'title'); this.gametitle.anchor.set(0.5,0); this.startbutton = this.add.button(ball._width*0.5, 200, 'button-start', this.startgame, this, 2, 0, 1); this.startbutton.anchor.set(0.5,0); this.startbutton.input.usehandcursor = tr...
...And 2 more matches
Adding features to our bouncing balls demo - Learn web development
remember to set the ball() constructor's prototype and constructor appropriately.
... 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.
...it will work in a very similar way, so you can start by copying the ball.prototype.draw definition.
...And 2 more matches
Rhino serialization
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.
...And 2 more matches
JIT Optimization Outcomes
noprotofound a prototype object was not found for all the object used by this operation.
... multiprotopaths objects used in this operation had differing prototypes.
... protoindexedprops the object being accessed has indexed properties that are exotic (for example, defined as a property on a prototype object and left as a hole in the underlying object).
...And 2 more matches
JSAPI Cookbook
/* 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_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.
...And 2 more matches
JSAPI User Guide
the prototype * passed in is null, so the default object prototype will be used.
....; 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.
...And 2 more matches
JS::CreateError
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.
...And 2 more matches
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.
... js::identifystandardprototype determines if the given object is a prototype for a standard class.
...And 2 more matches
JSClass.flags
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).
... 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.
...And 2 more matches
JSObjectOps.setProto
the jsobjectops.setproto and setparent callbacks implement the js_setprototype and js_setparent functions.
... 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 prototype or parent is being modified.
...And 2 more matches
JS_ConstructObject
create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object.
... proto jsobject * the object to serve as the new object's prototype, or null.
... 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.
...And 2 more matches
JS_NewObjectForConstructor
this must be an object that has a prototype property.
...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.
...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
Shell global objects
this is what debugger.source.prototype.elementattributename returns.
...this is what debugger.source.prototype.elementattributename returns.
... wrapwithproto(obj) wrap an object into a noop wrapper with prototype semantics.
...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; ...
...gle.bind(this); list.onclick = this.updatevalue.bind(this); document.addeventlistener('click', clickout); this.state = 0; this.time = 0; this.dropmenu = list; this.select = select; this.toggle(false); this.value = {}; this.topic = topic; if (label) select.textcontent = label; else this.setnodevalue(list.children[selected]); dropdowns[topic] = this; }; dropdown.prototype.toggle = function toggle(state) { if (typeof(state) === 'boolean') this.state = state === false ?
...!== 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
Enumerability and ownership of properties - JavaScript
ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain.
... property enumerability and ownership - built-in methods of detection, retrieval, and iteration functionality own object own object and its prototype chain prototype chain only detection enumerable nonenumerable enumerable and nonenumerable propertyisenumerable hasownproperty hasownproperty – filtered to exclude enumerables using propertyisenumerable hasownproperty ...
...y or just this: return object.keys(obj); }, getownnonenumerables: function(obj) { return this._getpropertynames(obj, true, false, this._notenumerable); }, getownenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, true, false, this._enumerableandnotenumerable); // or just use: return object.getownpropertynames(obj); }, getprototypeenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerable); }, getprototypenonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._notenumerable); }, getprototypeenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerableandnotenumerable); ...
...And 2 more matches
Public class fields - JavaScript
as such, unlike their private counterparts, they participate in prototype inheritance.
... 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.
...just as in public instance methods, if you're in a subclass you can access the superclass prototype using super.
...And 2 more matches
Deprecated and obsolete features - JavaScript
string methods html wrapper methods like string.prototype.fontsize and string.prototype.big.
... string.prototype.quote is removed from firefox 37.
... non standard flags parameter in string.prototype.search, string.prototype.match, and string.prototype.replace are deprecated.
...And 2 more matches
TypeError: Reduce of empty array with no initial value - JavaScript
in javascript, there are several reduce functions: array.prototype.reduce(), array.prototype.reduceright() and typedarray.prototype.reduce(), typedarray.prototype.reduceright()).
... examples invalid cases this problem appears frequently when combined with a filter (array.prototype.filter(), typedarray.prototype.filter()) which will remove all elements of the list.
... similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list: var names = document.getelementsbyclassname("names"); var name_list = array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); valid cases these problems can be solved in two different ways.
...And 2 more matches
Function - JavaScript
instance methods function.prototype.apply(thisarg [, argsarray]) calls a function and sets its this to the provided thisarg.
... function.prototype.bind(thisarg[, arg1[, arg2[, ...argn]]]) creates a new function which, when called, has its this set to the provided thisarg.
... function.prototype.call(thisarg[, arg1, arg2, ...argn]) calls a function and sets its this to the provided value.
...And 2 more matches
Intl.DateTimeFormat - JavaScript
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.
...And 2 more matches
Object.defineProperty() - JavaScript
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).
...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.
... function myclass() { } var value; object.defineproperty(myclass.prototype, "x", { get() { return value; }, set(x) { value = x; } }); var a = new myclass(); var b = new myclass(); a.x = 1; console.log(b.x); // 1 this can be fixed by storing the value in another property.
...And 2 more matches
WeakMap - JavaScript
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.
...And 2 more matches
WebAssembly.Global - JavaScript
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.
... global.prototype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global".
...And 2 more matches
WebAssembly.Table - JavaScript
instance properties table.prototype.length returns the length of the table, i.e.
... 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.
...And 2 more matches
Private Properties - Archive of obsolete content
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.
...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.
...using namespaces, the earlier example can be rewritten as: let map = new weakmap(); let internal = function (object) { if (!map.has(object)) map.set(object, {}); return map.get(object); } function point(x, y) { internal(this).x = x; internal(this).y = y; } point.prototype.getx = function () { return internal(this).x; }; point.prototype.setx = function (x) { internal(this).x = x; }; point.prototype.gety = function () { return internal(this).y; }; point.prototype.sety = function (y) { internal(this).y = y; }; the only way for a function to access the properties x and y, is if it has a reference to an instance of point and its internal namespace.
...to illustrate this, the following reimplements the class point using namespaces: const { ns } = require("sdk/core/namespace"); var internal = ns(); function point(x, y) { internal(this).x = x; internal(this).y = y; } point.prototype.getx = function () { return internal(this).x; }; point.prototype.setx = function (x) { internal(this).x = x; }; point.prototype.gety = function () { return internal(this).y; }; point.prototype.sety = function () { internal(this).y = y; }; as a final note, the function ns returns a namespace that uses the namespace associated with the prototype of the object as its prototype.
core/promise - Archive of obsolete content
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 pass...
...ed a second optional prototype argument to achieve the same effect.
... 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.
...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
function canvas2dcontext(canvas) { if (typeof canvas === 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canvas2dcontext.setup.call(this, this.ctx); } } canvas2dcontext.setup = function() { var methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transf...
...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 ===...
... 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.addeventlistener('load', this.remotepageloaded, true); //append to the end of the page window.document.body.appendchild(iframe); return; }; remotecanvas.prototype.remotepageloaded = function() { // look back up the iframe by id var ldrframe = document.getelementbyid('test-iframe'); // get a reference to the window object you need for the canvas // drawwindow method var remotewindow = ldrframe.contentwindow; //draw canvas var canvas = document.createelement('canvas'); canvas.style.width = remotecanvas.canvas_width + 'px'; canvas.style.height = remotecanvas.canvas_height + 'px'; canvas.width = remotecanvas.canvas_width; canvas.height = remotecanvas.canvas_height; var windowwidth...
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.
... // 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); ...
...}; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodename); // gi...
...ves 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodename); // 'a' xul example: <hbox><vbox/></hbox> <script type="text/javascript"><![cdata[ element.prototype.$ = function (selector) { return this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodename); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('somens', 'foo')[0];...
Appendix D: Loading Scripts - Archive of obsolete content
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.
...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.
... const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest", "open"); function loadscript(name, context) { // create the sandbox let sandbox = components.utils.sandbox(context, { sandboxprototype: context, wantxrays: false }); // get the caller's filename let file = components.caller.stack.filename; // strip off any prefixes added by the sub-script loader // and the trailing filename let directory = file.replace(/.* -> |[^\/]+$/g, ""); let scriptname = directory + name; // read the script let xmlhttp = xmlhttprequest("get", scriptname, false);...
... function loadscript(name, context) { // create the sandbox let sandbox = components.utils.sandbox(context, { sandboxprototype: context, wantxrays: false }); // get the caller's filename let file = components.caller.stack.filename; // strip off any prefixes added by the sub-script loader // and the trailing filename let directory = file.replace(/.* -> |[^\/]+$/g, ""); services.scriptloader.loadsubscript(directory + name, sandbox, "utf-8"); } l...
The global XML object - Archive of obsolete content
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.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default.
New in JavaScript 1.2 - Archive of obsolete content
arguments new properties function.arity new methods array.prototype.concat() array.prototype.slice() string.prototype.charcodeat() string.prototype.concat() string.fromcharcode() string.prototype.match() string.prototype.replace() string.prototype.search() string.prototype.slice() string.prototype.substr() new operators delete equality operators (== and !=) new statements labeled statements switch do...while import export other new featu...
... array.prototype.sort() now works on all platforms.
... string.prototype.split() it can take a regular expression argument, as well as a fixed string, by which to split the object string.
... string.prototype.substring(): no longer swaps index numbers when the first index is greater than the second.
Index - Learn web development
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.
... 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 topic...
... 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.
Object building practice - Learn web development
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).
...add the following code at the bottom of your javascript file, to add an update() method to the ball()'s prototype: ball.prototype.update = function() { if ((this.x + this.size) >= width) { this.velx = -(this.velx); } if ((this.x - this.size) <= 0) { this.velx = -(this.velx); } if ((this.y + this.size) >= height) { this.vely = -(this.vely); } if ((this.y - this.size) <= 0) { this.vely = -(this.vely); } this.x += this.velx; this.y += this.vely; } the first four parts o...
... first, add the following method definition below where you defined the update() method (i.e., the ball.prototype.update block).
... ball.prototype.collisiondetect = function() { for (let j = 0; j < balls.length; j++) { if (!(this === balls[j])) { const dx = this.x - balls[j].x; const dy = this.y - balls[j].y; const distance = math.sqrt(dx * dx + dy * dy); if (distance < this.size + balls[j].size) { balls[j].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) +')'; } } } } this method is a little complex, so don't worry if you don't understand exactly how it works for now.
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...
NSS API Guidelines
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.
... 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.
...likewise, the external references to errors are made in the prototypes files, with the functions which can return them.
sslfnc.html
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.
... 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.
... 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.
... 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.
Self-hosted builtins in SpiderMonkey
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.
... 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.
...a prototype property can be added from the self-hosted code itself.
...you can not, for example, use function.prototype.apply directly.
JSObject
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).
...the term own property refers to a property of an object that is not inherited from its prototype.
Building an Account Manager Extension
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...
...devmoaccountmanagerextension.prototype.classid = components.id("{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ...
...devmoaccountmanagerextension.prototype.classdescription = "devmo account manager extension"; // ...
...devmoaccountmanagerextension.prototype.contractid = "@mozilla.org/accountmanager/extension;1?name=example@mozilla.org"; // add the component to the mailnews-accountmanager-extensions category devmoaccountmanagerextension.prototype._xpcom_categories: [{ category: "mailnews-accountmanager-extensions" }], // create entry point for the module if (xpcomutils.generatensgetfactory) var nsgetfactory = xpcomutils.generatensgetfactory([devmoaccountmanagerextension]); else var nsgetmodule = xpcomutils.generatensgetmodule([devmoaccountmanagerextension]); step3: create the new panel as next step we create the xul and the property file for your new panel.
Debugger - Firefox Developer Tools
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.
... 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.
...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.
...determine which global is designated byglobal using the same rules as debugger.prototype.adddebuggee.
EventTarget.addEventListener() - Web APIs
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.
... 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.
... (function() { if (!event.prototype.preventdefault) { event.prototype.preventdefault=function() { this.returnvalue=false; }; } if (!event.prototype.stoppropagation) { event.prototype.stoppropagation=function() { this.cancelbubble=true; }; } if (!element.prototype.addeventlistener) { var eventlisteners=[]; var addeventlistener=function(type,listener /*, usecapture (will be ignored) */) { ...
...this && eventlistener.type==type && eventlistener.listener==listener) { if (type=="domcontentloaded") { this.detachevent("onreadystatechange",eventlistener.wrapper); } else { this.detachevent("on"+type,eventlistener.wrapper); } eventlisteners.splice(counter, 1); break; } ++counter; } }; element.prototype.addeventlistener=addeventlistener; element.prototype.removeeventlistener=removeeventlistener; if (htmldocument) { htmldocument.prototype.addeventlistener=addeventlistener; htmldocument.prototype.removeeventlistener=removeeventlistener; } if (window) { window.prototype.addeventlistener=addeventlistener; window.prototype.removeeventlistener=removeeventlistene...
TextDecoder - Web APIs
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.
... textdecoder.prototype.decode() returns a domstring containing the text decoded with the method of the specific textdecoder object.
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 + '"]'); ...
... 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.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)); break...
... #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 + '"]'); ...
... 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.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)); break...
Boolean - JavaScript
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.
Intl.Collator - JavaScript
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.
... using locales the results provided by collator.prototype.compare() vary between languages.
... 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...
Object.assign() - JavaScript
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.
...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...
...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.
Object.preventExtensions() - JavaScript
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.
...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'.
Promise - JavaScript
as the promise.prototype.then() and promise.prototype.catch() methods return promises, they can be chained.
... 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.
... promise.prototype.finally() appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved.
Reflect - JavaScript
see also function.prototype.apply().
...also provides the option to specify a different prototype.
... reflect.getprototypeof(target) same as object.getprototypeof().
... reflect.setprototypeof(target, prototype) a function that sets the prototype of an object.
Symbol.toStringTag - JavaScript
it is accessed internally by the object.prototype.tostring() method.
... 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 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 more custom classes default to object tag when creating your own class, javascript defaults to the "object" tag: class validatorclass {} object.prototype.tostring.call(new validatorclass()); // "[object object]" custom tag with tostringtag now, with the help of tostringtag, you are able to set your own custom tag: class validatorclass { get [symbol.tostringtag]() { return 'validator'; } } object.prototype.tostring.call(new validatorclass()); // "[object validator]" tostringtag available on all dom prototype objects due to a webidl spec change in mid-2020, browsers are adding a symbol.tostringtag property to all dom prototype objects.
WeakSet - JavaScript
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.
in operator - JavaScript
the in operator returns true if the specified property is in the specified object or its prototype chain.
... object object to check if it (or its prototype chain) contains the property with specified name (prop).
... 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.
new operator - JavaScript
when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype.
... you can add a shared property to a previously defined object type by using the function.prototype property.
...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.
for...of - JavaScript
ssed into a javascript function: (function() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 iterating over a dom collection iterating over dom collections like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.iterator] const articleparagraphs = document.queryselectorall('article > p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of loops, abrupt iteration termination can be caused by break, throw or return.
... object.prototype.objcustom = function() {}; array.prototype.arrcustom = function() {}; const iterable = [3, 5, 7]; iterable.foo = 'hello'; for (const i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrcustom", "objcustom" } for (const i in iterable) { if (iterable.hasownproperty(i)) { console.log(i); // logs 0, 1, 2, "foo" } } for (const i of iterable) { console.log(i); // logs 3, 5, 7 }...
... object.prototype.objcustom = function() {}; array.prototype.arrcustom = function() {}; const iterable = [3, 5, 7]; iterable.foo = 'hello'; every object will inherit the objcustom property and every object that is an array will inherit the arrcustom property since these properties have been added to object.prototype and array.prototype, respectively.
... the object iterable inherits the properties objcustom and arrcustom because of inheritance and the prototype chain.
JavaScript typed arrays - JavaScript
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.
... 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.
... 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
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.
... 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.
test/assert - Archive of obsolete content
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.
... 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.
... to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thrown must match the regular expression for example, suppose we define two different custom exceptions: function myerror(message) { this.name = "myerror"; this.message = message || "default message"; } myerror.prototype = new error(); myerror.prototype.constructor = myerror; function anothererror(message) { this.name = "anothererror"; this.message = message || "default message"; console.log(this.message); } anothererror.prototype = new error(); anothererror.prototype.constructor = anothererror; we can check the type of exception by passing a function as the error argument: exports["test exception typ...
Preferences - Archive of obsolete content
var prefservice = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); this._branch = prefservice.getbranch(branch_name); 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('', {}).
... foreach(function (pref_leaf_name) { that._callback(that._branch, pref_leaf_name); }); } }; preflistener.prototype.unregister = function() { if (this._branch) this._branch.removeobserver('', this); }; var mylistener = new preflistener( "extensions.myextension.", function(branch, name) { switch (name) { case "pref1": // extensions.myextension.pref1 was changed break; case "pref2": // extensions.myextension.pref2 was changed break; } } ); mylistener.register(true); note: you need to keep a reference to the preference branch you are observing (unless it is the root branch) or it will get garbage collected and will never notify you.
Promises - Archive of obsolete content
*/ jsonstore.prototype.flush = function () { return this.saver.flush(); }; /** * queue a save operation.
... */ jsonstore.prototype.save = function () { return this.saver.savechanges(); }; example usage: var addon_id = "extension@example.com"; var config_default = { "foo": "bar", }; new jsonstore("config", config_default).then(store => { console.log(store.data); store.data.baz = "quux"; store.save(); }) the following changes will remove the dependency on aom wrappers: let addon = yield new promise(accept => addonmanager.getaddonbyid(addon_id, accept)); let dir = yield new promise(accept => addon.getdatadirectory(accept)); xmlhttprequest funct...
...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", ...
Venkman Introduction - Archive of obsolete content
this is the same text you would get from the tosource method of the function prototype.
... 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.
How to implement a custom XUL query processor component - Archive of obsolete content
here is our sample javascript xpcom query processor: components.utils.import("resource://gre/modules/xpcomutils.jsm"); // basic wrapper for nsixultemplateresult function templateresult(adata) { this._data = adata; // just make a random number for the id this._id = math.random(100000).tostring(); } templateresult.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsixultemplateresult]), // private storage _data: null, // right now our results are flat lists, so no containing/recursion take place iscontainer: false, isempty: true, mayprocesschildren: false, resource: null, type: "simple-item", get id() { return this._id; }, // return the value of that bound var...
... rulematched: function(aquery, arulenode) { }, // the output for a result has been removed and the result is no longer being used by the builder hasbeenremoved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsisimpleenumerator]), hasmoreelements: function() { return this._index < this._array.length; }, getnext: function() { return new templateresult(this._array[this._index++]); } }; // the query processor class - implements nsixultemplatequeryprocessor function templatequeryprocessor() { // our basic list of dat...
...a 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) { // todo: parse the adatasources variable // for now, ignor...
Iterator - Archive of obsolete content
keyonly if keyonly is truthy value, iterator.prototype.next returns property_name only.
... 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.
New in JavaScript 1.8.5 - Archive of obsolete content
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 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).
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... 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.
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
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).
...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.
Object-oriented JavaScript for beginners - Learn web development
to avoid this, we can define functions on the prototype instead, which we will look at later.
... in the next article, we'll explore javascript object prototypes.
... previous overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
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.
...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 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.
Displaying Places information using views
the built-in tree view is backed by an instance of placestreeview, a prototype defined in browser/components/places/content/treeview.js.
...the javascript prototype backing the built-in view, placestreeview, is especially useful since it implements all three of nsinavhistoryresulttreeviewer, nsinavhistoryresultobserver, and nsitreeview.
...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.
Log.jsm
class overview appender(); length: 1 keys of prototype: append(); doappend(); level: 0 basicformatter(); length: 1 keys of prototype: format(); boundedfileappender(); length: 2 keys of prototype: doappend(); reset(); ...
... consoleappender(); length: 1 keys of prototype: doappend(); dumpappender(); length: 1 keys of prototype: doappend(); fileappender(); length: 2 keys of prototype: doappend(); reset(); formatter(); length: 0 keys of prototype: format(); logmessage(); length: 4 keys of prototype: leveldesc logger(); length: 2 keys of prototype: addappender(); level logstructured(); name ...
... parent removeappender(); updateappenders(); and the methods mentioned below: logger methods loggerrepository(); length: 0 keys of prototype: getlogger(); rootlogger storagestreamappender(); length: 1 keys of prototype: doappend(); getinputstream(); newoutputstream(); outputstream reset(); structuredformatter(); length: 0 keys of prototype: format(); method overview enumerateinterfaces(); length: 0 ...
PromiseWorker.jsm
// 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.
... // main thread // define a custom error prototype.
XPCOMUtils.jsm
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).
...for example, if your component implements nsistreamconverter: mycomponent.prototype = { queryinterface: xpcomutils.generateqi([ components.interfaces.nsirequestobserver, components.interfaces.nsistreamlistener, components.interfaces.nsistreamconverter, ]), // ...methods...
Rhino overview
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).
... string.prototype.substring for version 1.2 only, the two arguments are not swapped if the first argument is less than the second one.
... 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).
JIT Optimization Strategies
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.
... 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.
JSExtendedClass.wrappedObject
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).
... 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
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.
...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 define the property id being resolved in the object in which the id was first sought, rather than in a prototype object whose class led to the resolve hook being called.
JSPropertyOp
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.
... jsclass.getproperty is also called when a program attempts to get a property that does not exist on obj or any prototype.
JS_GetClassObject
key jsprotokey the key of the prototype.
... description js_getclassobject gets the builtin class costructor for the specified prototype key.
... see also mxr id search for js_getclassobject js_getclassprototype jsprotokey ...
JS_GetLocaleCallbacks
e)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocalecompare)(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.
JS_LookupProperty
this will be either obj or an element on obj's prototype chain.
...these functions all have similar behavior: the search starts with obj and proceeds along the prototype chain.
... 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).
Property attributes
(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 property is also jsprop_permanent, then certain aspects of inheriting the property via the prototype chain are affected.
SpiderMonkey 1.8
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.
... 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.
XPCOM changes in Gecko 2.0
for example, in your component's javascript code : components.utils.import("resource://gre/modules/xpcomutils.jsm"); function mycomponent() { } mycomponent.prototype = { // this must match whatever is in chrome.manifest!
...each component prototype // must have a .classid which is used to create it.
...therefore the following categories have changed: old name new name javascript global constructor javascript-global-constructor javascript global constructor prototype alias javascript-global-constructor-prototype-alias javascript global property javascript-global-property javascript global privileged property javascript-global-privileged-property javascript global static nameset javascript-global-static-nameset javascript global dynamic nameset javascript-global-dynamic-nameset javascript dom class javascript-dom-class javascript dom interface ja...
Components.utils.Sandbox
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.
... sandboxprototype a prototype object for the sandbox.
... var sandboxscript = 'alert($)'; var options = { sandboxprototype: content, wantxrays: false // only set this to false if you need direct access to the page's javascript.
nsIHttpHeaderVisitor
mynsihttpheadervisitor = function ( ) { this._isflash = false; }; mynsihttpheadervisitor.prototype.visitheader = function ( aheader, avalue ) { if ( aheader.indexof( "content-type" ) !== -1 ) { if ( avalue.indexof( "application/x-shockwave-flash" ) !== -1 ) { this._isflash = true; } } }; mynsihttpheadervisitor.prototype.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!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { v...
...ar 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 ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.removeobserver( this, "http-on-examine-response" ); observerservice.removeobserver(this, "http-on-examine-cached-response"); }; see also nsihttpchannel ...
nsIXPCScriptable
appednative wrapper, in jstracerptr trc, in jsobjectptr obj); prbool equality(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval val); jsobjectptr outerobject(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); jsobjectptr innerobject(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); void postcreateprototype(in jscontextptr cx, in jsobjectptr proto); attributes attribute type description classname string scriptableflags pruint32 the bitwise or'd set of flags (define below) that indicate the behavior of this object.
... 1 << 14 want_hasinstance 1 << 15 want_trace 1 << 16 use_jsstub_for_addproperty 1 << 17 use_jsstub_for_delproperty 1 << 18 use_jsstub_for_setproperty 1 << 19 dont_enum_static_props 1 << 20 dont_enum_query_interface 1 << 21 dont_ask_instance_for_scriptable 1 << 22 classinfo_interfaces_only 1 << 23 allow_prop_mods_during_resolve 1 << 24 allow_prop_mods_to_prototype 1 << 25 dont_share_prototype 1 << 26 dont_reflect_interface_names 1 << 27 want_equality 1 << 28 want_outer_object 1 << 29 want_inner_object 1 << 30 reserved 1 << 31 the high order bit is reserved for consumers of these flags.
...if an implementation of this method throws an error code, the prototype chain will not be checked for the property.
Debugger.Memory - Firefox Developer Tools
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.
... you can retrieve the allocation site for a given object with the debugger.object.prototype.allocationsite accessor property.
... 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.
Debugger.Script - Firefox Developer Tools
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.
...for function.prototype’s script, this is null.
... 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.
Debugger.Source - Firefox Developer Tools
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.
...for function.prototype’s script, this is null.
... "function.prototype", for function.prototype internally generated code.
ChildNode.after() - Web APIs
WebAPIChildNodeafter
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.prototype, documenttype.prototype]); another polyfill // from: https://github.com/fabiovergani/js-polyfill_element.prototype.after/blob/master/after.js (function(x){ var o=x.prototype,p='after'; if(!o[p]){ o[p]=function(){ var e, m=arguments, l=m.length, i=0, t=this, p=t.parentnode, n=node, s=string, d=document; if(p!==null){ while(i<l){ e=m[i]; if(e instanceof n){ t=t.nextsibling; if(t!==null){ p.insertbefore(e,t); }else{ p.appendchild(e); }; }else{ p.appendchild(d.c...
...reatetextnode(s(e))); }; ++i; }; }; }; }; })(element); /* minified: (function(x){ var o=x.prototype; o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentnode,n=node,s=string,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextsibling )!==null)?p.insertbefore(e,t):p.appendchild(e)):p.appendchild(d.createtextnode(s(e)));++i;}}}); }(element)); */ specification specification status comment domthe definition of 'childnode.after()' in that specification.
Overview of events and handlers - Developer guides
browsers use as the data structure for the properties of the event, an object derived from the eventprototype object.
..."eventprototype" : "objectprototype"; alert("we got a click event at " + ev.timestamp + " with an argument object derived from: " + objkind ); }; and second register our function with the the button object, either on the scripting side using the dom (document object model) representation of the html page: var buttondomelement = document.queryselector('#buttonone'); buttondomelement.addeventlistener('click'...
...each definition includes, as the data structure passed to the handler function, an object which inherits from the eventprototype object.
About JavaScript - JavaScript
it is a prototype-based, multi-paradigm scripting language that is dynamic, and supports object-oriented, imperative, and functional programming styles.
...in a nutshell, javascript is a dynamic scripting language supporting prototype based object construction.
...once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects.
Closures - JavaScript
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.
... 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.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.
Introduction - JavaScript
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.
...inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.
Keyed collections - JavaScript
an object has a prototype, so there are default keys in the map.
...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`...
Numbers and dates - JavaScript
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.
TypeError: "x" is not a function - JavaScript
you will have to provide a function in order to have these methods working properly: when working with array or typedarray objects: array.prototype.every(), array.prototype.some(), array.prototype.foreach(), array.prototype.map(), array.prototype.filter(), array.prototype.reduce(), array.prototype.reduceright(), array.prototype.find() when working with map and set objects: map.prototype.foreach() and set.prototype.foreach() examples a typo in the function name in this case, which happens way too often, there is a typo i...
...in this example, array.prototype.map() is used, which will work with array objects only.
... var dog = function () { this.age = 11; this.color = "black"; this.name = "ralph"; return this; } dog.prototype.name = function(name) { this.name = name; return this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //uncaught typeerror: mynewdog.name is not a function use a different property name instead: var dog = function () { this.age = 11; this.color = "black"; this.dogname = "ralph"; //using this.dogname instead of .name return this; } dog.prototype.name = function(name) { this.dog...
The arguments object - JavaScript
however, it can be converted to a real array: var args = array.prototype.slice.call(arguments); // using an array literal is shorter than above but allocates an empty array var args = [].slice.call(arguments); as you can do with any array-like object, you can use es2015's array.from() method or spread syntax to convert arguments to a real array: let args = array.from(arguments); // or let args = [...arguments]; the arguments object is useful for functions called ...
... 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.
...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.
Generator - JavaScript
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).
Intl.NumberFormat - JavaScript
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.
Intl.RelativeTimeFormat - JavaScript
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.
Object.freeze() - JavaScript
in addition, freezing an object also prevents its prototype from being changed.
...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.
Reflect.apply() - JavaScript
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, 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.
Symbol.matchAll - JavaScript
this function is called by the string.prototype.matchall() method.
... description this symbol is used for string.prototype.matchall() and specifically in regexp.prototype[@@matchall]().
... enumerable no configurable no examples using symbol.matchall let re = /[0-9]+/g; let str = '2016-01-02|2019-03-07'; const numbers = { *[symbol.matchall] (str) { for (const n of str.matchall(/[0-9]+/g)) yield n[0]; } }; console.log(array.from(str.matchall(numbers))); // array ["2016", "01", "02", "2019", "03", "07"] see string.prototype.matchall() and regexp.prototype[@@matchall]() for more examples.
Symbol.unscopables - JavaScript
however, in ecmascript 2015 and later, the array.prototype.keys() method 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.
/loader - Archive of obsolete content
prototype: object that the returned sandbox will inherit from.
... 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.
lang/type - Archive of obsolete content
isflat(value) returns true if value is a direct descendant of object.prototype or null.
... returns boolean : boolean indicating if value is a direct descendant of object.prototype or null.
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...
... 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.
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
these often include areas such as: object prototypes, such as string.prototype, which are often extended to add methods to native objects.
...scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts.
Offering a context menu for form controls - Archive of obsolete content
window.addeventlistener("load", function() { let settargetoriginal = nscontextmenu.prototype.settarget; 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.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
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.
...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
javascript is a prototype-based object-oriented language, and as shown in listing 3, also permits independent class definitions.
... 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.
JavaScript Object Management - Archive of obsolete content
*/ 〈modulenamespace〉.user.prototype = { /* the name of the user.
...the definition of the class acts as a constructor as well, and then you can define all other members using the prototype attribute.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ys/pureshuffle.html */ here's how the ldap fail-over works: // 2) setup multiple ldap servers for fail-over var ldap_values; var ldap_servers = 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 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); ....
... 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
<html> <head> <title>wifi monitor example</title> <script> var count = 0; function test() { } test.prototype = { onchange: function (accesspoints) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var d = document.getelementbyid("d"); d.innerhtml = ""; for (var i=0; i<accesspoints.length; i++) { var a = accesspoints[i]; d.innerhtml += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getelementbyid("c"); c.i...
...ger.enableprivilege('universalxpconnect'); var listener = new test(); var wifi_service = components.classes["@mozilla.org/wifi/monitor;1"].getservice(components.interfaces.nsiwifimonitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> the nsiwifilistener object the first thing the code above does is to prototype the listener object that will be receiving notifications of changes to the access point list.
Dehydra Object Reference - Archive of obsolete content
variables can identified by their dehydradecl() prototype.
...dehydra type objects use the dehydratype() prototype.
XULRunner Hall of Fame - Archive of obsolete content
mockery mockery is a gui design tool for creating and editing mockups, prototypes, and wireframes for web and desktop software.
...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.
New in JavaScript 1.1 - Archive of obsolete content
--> 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.
... constructor and prototype properties on objects added.
Object.observe() - Archive of obsolete content
if omitted, the array ["add", "update", "delete", "reconfigure", "setprototype", "preventextensions"] will be used.
...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...
Test your skills: Object-oriented JavaScript - Learn web development
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.
...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.
Introducing JavaScript objects - Learn web development
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.
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...
...} myclass.prototype.streamlistener = function (acallbackfunc) { return ({ mdata: "", // ...
PR_EXTERN
used to define the prototypes for functions or variables that are to be exported from a shared library.
... syntax #include <prtypes.h> pr_extern(type)prototype description pr_extern is used to define externally visible routines and globals.
NSS_3.12_release_notes.html
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 132485: built-in root certs slot description is empty bug 177184: nss_cmsdecoder_cancel might have a leak bug 232392: erroneous root ca tests in nss libraries bug 286642: util should be in a shared library bug 287052: function to get crl entry reason code has incorrect prototype and implementation bug 299308: need additional apis in the crl cache for libpkix bug 335039: nssckfwcryptooperation_updatecombo is not declared bug 340917: crlutil should init nss read-only for some options bug 350948: freebl macro change can give 1% improvement in rsa performance on amd64 bug 352439: reference leaks in modutil bug 369144: certutil needs option to generate subjectkeyid extension ...
Invariants
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.
... 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.
JS::CloneFunctionObject
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.
JS::ProtoKeyToId
key jsprotokey the prototype key to convert.
... description js::protokeytoid converts a specified js prototype key key, to a js id.
JSClass
to do this, use the jsclass_has_private (jsclass_construct_prototype wad removed) flags.
... * 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 ...
JSObjectOps.getProperty
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.
... 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).
JSObjectOps.lookupProperty
description look for id in obj and its prototype chain, returning js_false on error or exception, js_true on success.
...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.
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.
JS_CloneFunctionObject
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.
JS_GetPropertyDescriptor
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.
JS_HasInstance
obj js::handle&lt;jsobject*&gt; constructor/prototype to test.
...when providing a prototype as obj, the prototype's jsclass must have its hasinstance method set.
JS_IsConstructing_PossiblyWithGivenThisObject
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.
...blywithgiventhisobject(cx, vp, &maybethis)) { // native called as a constructor if (maybethis) // native called as a constructor with maybethis as 'this' } else { // native called as function, maybethis is still uninitialized } } note: a spidermonkey embedding does not need to use this query unless the embedding uses js_constructobject(), js_initclass() and jsclass_construct_prototype as described above.
JS_ValueToId
key jsprotokey the prototype key to convert.
... js::protokeytoid converts a specified prototype key to a jsid.
SpiderMonkey 24
new c apis js_getarrayprototype provides access to the original value of array.prototype.
... 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.
SavedFrame
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.
... function properties of the savedframe.prototype object tostring return this frame and its parents formatted as a human readable stack trace string.
How to build an XPCOM component in JavaScript
modifications so that xpcomutils can set it up properly: /*********************************************************** class definition ***********************************************************/ //class constructor function helloworld() { // if you only need to access your component from javascript, uncomment the following line: //this.wrappedjsobject = this; } // class definition helloworld.prototype = { // properties required for xpcom registration: classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an object implementing nsifactory).
...// 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
// 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.
... 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.
Activity Manager examples
} canceljunkprocess.prototype = { cancel: function(aactivity) { let initiator = aactivity.initiator; if (initiator) { let folder = aactivity.getsubjects({})[0]; ....
...} sendercontextdisplayhelper.prototype = { getcontextdisplaytext: function(contexttype, contextobj) { // in this particular example we know that contexttype is "sender" // since we also pass the contexttype along with the contextobject // in some cases, one helper can be registered for a group of context types // we know that the context object is the author of the message // localization is omitted return "messag...
Working with ArrayBuffers
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.
Mozilla
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.
...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).
Debugger.Environment - Firefox Developer Tools
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.
... 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.
Index - Firefox Developer Tools
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.
...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.
Dominators view - Firefox Developer Tools
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.
ChildNode.before() - Web APIs
WebAPIChildNodebefore
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, documenttype.prototype]); specification specification status comment domthe definition of 'childnode.before()' in that specification.
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 used method of operation.
Element.closest() - Web APIs
WebAPIElementclosest
> 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...
... if (window.element && !element.prototype.closest) { element.prototype.closest = function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i, el = this; do { i = matches.length; while (--i >= 0 && matches.item(i) !== el) {}; } while ((i < 0) && (el = el.parentelement)); return el; }; } specifications specification status comment domthe definition of 'element.closest()' in that specification.
Element.getElementsByClassName() - Web APIs
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.
Element.matches() - Web APIs
WebAPIElementmatches
polyfill for browsers that do not support element.matches() or element.matchesselector(), but include support for document.queryselectorall(), a polyfill exists: if (!element.prototype.matches) { element.prototype.matches = element.prototype.matchesselector || element.prototype.mozmatchesselector || element.prototype.msmatchesselector || element.prototype.omatchesselector || element.prototype.webkitmatchesselector || function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i = matches.length...
... if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatchesselector || element.prototype.webkitmatchesselector; } specification specification status comment domthe definition of 'element.prototype.matches' in that specification.
EventTarget - Web APIs
void seteventhandler(domstring type, eventhandler 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 stack = this.listeners[event.type].slice(); for (var i = 0, l = stack.length; i < l; i++) { stack[i].call(this, event); } return !event.defaultprevented; }; specifications specification status comment domthe definition of 'eventtarget' in that specification.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else sta...
... we can ensure consistent ordering of these operations by using a microtask in the if clause to balance the two clauses: customelement.prototype.getdata = url => { if (this.cache[url]) { queuemicrotask(() => { this.data = this.cache[url]; this.dispatchevent(new event("load")); }); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; this balances the clauses by having both situat...
KeyboardEvent.isComposing - Web APIs
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.
NodeList - Web APIs
WebAPINodeList
this can be circumvented by using array.prototype.foreach() — see this document's example.
... 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.
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) { ...
...rty('nextelementsibling')) { return; } object.defineproperty(item, 'nextelementsibling', { configurable: true, enumerable: true, get: function () { var el = this; while (el = el.nextsibling) { if (el.nodetype === 1) { return el; } } return null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'childnodenextelementsibling' in that specification.
NonDocumentTypeChildNode.previousElementSibling - Web APIs
div polyfills 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(!("previouselementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "previouselementsibling", { get: function(){ var e = this.previoussibling; while(e && 1 !== e.nodetype) e = e.previoussibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/previouselementsibling/previouselementsibling.md (function (arr) { arr.foreach(fun...
...ouselementsibling')) { return; } object.defineproperty(item, 'previouselementsibling', { configurable: true, enumerable: true, get: function () { let el = this; while (el = el.previoussibling) { if (el.nodetype === 1) { return el; } } return null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'nondocumenttypechildnode.previouselementsibling' in that specification.
ParentNode.append() - Web APIs
WebAPIParentNodeappend
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.prototype]); specification specification status comment domthe definition of 'parentnode.append()' in that specification.
ParentNode.children - Web APIs
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.
...;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { object.defineproperty(constructor.prototype, 'children', { get: function() { let i = 0, node, nodes = this.childnodes, children = []; while (node = nodes[i++]) { if (node.nodetype === 1) { children.push(node); } } return children; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.children' in that specification.
ParentNode.firstElementChild - Web APIs
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.
...;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.firstelementchild == null) { object.defineproperty(constructor.prototype, 'firstelementchild', { get: function() { var node, nodes = this.childnodes, i = 0; while (node = nodes[i++]) { if (node.nodetype === 1) { return node; } } return null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.firstelementchild' in that specification.
ParentNode.lastElementChild - Web APIs
// overwrites native 'lastelementchild' prototype.
...;(function(constructor) { if(constructor && constructor.prototype && constructor.prototype.lastelementchild == null) { object.defineproperty(constructor.prototype, 'lastelementchild', { get: function() { var node, nodes = this.childnodes, i = nodes.length - 1; while(node = nodes[i--]) { if(node.nodetype === 1) { return node; } } return null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.lastelementchild' in that specification.
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, documentfragment.prototype]); specification specification status comment domthe definition of 'parentnode.prepend()' in that specification.
RTCPeerConnection.getStreamById() - Web APIs
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.
... // from: https://bugs.chromium.org/p/chromium/issues/detail?id=698163&desc=5#c10 rtcpeerconnection.prototype.getstreambyid = function(id) { try { var localstreams = this.getlocalstreams(); var remotestreams = this.getremotestreams(); var i; for (i = 0; i < localstreams.length; i++) { if (localstreams[i].id == id) return localstreams[i]; } for (i = 0; i < remotestreams.length; i++) { if (remotestreams[i].id == id) return remotestreams[i]; } } catch(e) {} return null; } ...
Synchronous and asynchronous requests - Web APIs
*/) { var xhr = new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arguments, 2); xhr.onload = xhrsuccess; xhr.onerror = xhrerror; xhr.open("get", url, true); xhr.send(null); } usage: function showmessage(message) { console.log(message + this.responsetext); } loadfile("message.txt", showmessage, "new message!\n\n"); the signature of the utility function loadfile declares (i) a target url to read (via an http get request), (ii...
...this is done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); } ...
DOM onevent handlers - Developer guides
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.
Indexed collections - JavaScript
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.
Iterators and generators - JavaScript
this simply means that the object (or one of the objects up its prototype chain) must have a property with a symbol.iterator key.
...ield 1; }; user-defined iterables you can make your own iterables like this: const myiterable = { *[symbol.iterator]() { yield 1; yield 2; yield 3; } } for (let value of myiterable) { console.log(value); } // 1 // 2 // 3 or [...myiterable]; // [1, 2, 3] built-in iterables string, array, typedarray, map and set are all built-in iterables, because their prototype objects all have a symbol.iterator method.
Text formatting - JavaScript
see also string.fromcodepoint() or string.prototype.codepointat().
...(examples should be added to this page after mdn bug 857438 is fixed.) see also string.fromcodepoint() or string.prototype.codepointat().
constructor - JavaScript
this.name = 'square'; } get area() { return this.height * this.width; } set area(value) { this.height = value**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.
... 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.
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.
... the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified.
TypeError: More arguments needed - JavaScript
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.
... examples required arguments not provided the object.create() method requires at least one argument and the object.setprototypeof() method requires at least two arguments: var obj = object.create(); // typeerror: object.create requires at least 1 argument, but only 0 were passed var obj = object.setprototypeof({}); // typeerror: object.setprototypeof requires at least 2 arguments, but only 1 were passed you can fix this by setting null as the prototype, for example: var obj = object.create(null); var obj = object.setprototypeof({}, null); ...
RangeError: repeat count must be non-negative - JavaScript
the javascript exception "repeat count must be non-negative" occurs when the string.prototype.repeat() method is used with a count argument that is a negative number.
... the string.prototype.repeat() method has been used.
RangeError: precision is out of range - JavaScript
there was an out of range precision argument in one of these methods: number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() the allowed range for these methods is usually between 0 and 20 (or 21).
... method firefox (spidermonkey) chrome, opera (v8) number.prototype.toexponential() 0 to 100 0 to 20 number.prototype.tofixed() -20 to 100 0 to 20 number.prototype.toprecision() 1 to 100 1 to 21 examples invalid cases 77.1234.toexponential(-1); // rangeerror 77.1234.toexponential(101); // rangeerror 2.34.tofixed(-100); // rangeerror 2.34.tofixed(1001); // rangeerror 1234.5.toprecision(-1); // rangeerror 1234.5.toprecision(101); // rangeerror valid cases 77.1234.toexponential(4); // 7.7123e+1 77.1234.toexponential(2); // 7.71e+1 2.34.tofixed(1); // 2.3 2.35.tofixed(1); // 2.4 (note that it rounds up in this case) 5.123456.toprecisi...
RangeError: repeat count must be less than infinity - JavaScript
the javascript exception "repeat count must be less than infinity" occurs when the string.prototype.repeat() method is used with a count argument that is infinity.
... the string.prototype.repeat() method has been used.
TypeError: invalid 'instanceof' operand 'x' - JavaScript
an object which has a prototype property and is callable.
...an object which has a prototype property and is callable.
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...
...ypeerror: 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 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 ...
Arrow function expressions - JavaScript
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).
getter - JavaScript
when using get the property will 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.
AggregateError - JavaScript
instance properties aggregateerror.prototype.message error message, defaults to "".
... aggregateerror.prototype.name error name, defaults to aggregateerror.
Array.from() - JavaScript
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()).
...symbol.iterator : 'symbol(symbol.iterator)'; } catch { symboliterator = 'symbol(symbol.iterator)'; } var tostr = object.prototype.tostring; var iscallable = function (fn) { return ( typeof fn === 'function' || tostr.call(fn) === '[object function]' ); }; var tointeger = function (value) { var number = number(value); if (isnan(number)) return 0; if (number === 0 || !isfinite(number)) return number; ...
Array.isArray() - JavaScript
if (!array.isarray) { 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 it works through iframes.
ArrayBuffer - JavaScript
instance properties arraybuffer.prototype.bytelength the read-only size, in bytes, of the arraybuffer.
... 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).
AsyncFunction - JavaScript
it can be obtained with the following code: object.getprototypeof(async function(){}).constructor syntax new asyncfunction([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
... examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); specifications specification ecmascript (ecma-262)the definition of 'asyncfunction object' in that spec...
FinalizationRegistry - JavaScript
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.
GeneratorFunction - JavaScript
object.getprototypeof(function*(){}).constructor syntax new generatorfunction ([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
... 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.
Intl.DisplayNames - JavaScript
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.
Intl.ListFormat - JavaScript
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.
Intl.PluralRules - JavaScript
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.
Object.getOwnPropertyDescriptors() - JavaScript
examples creating a shallow clone whereas 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.
...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.
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.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.
handler.set() - JavaScript
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.
Proxy() constructor - JavaScript
handler.getprototypeof() a trap for object.getprototypeof.
... handler.setprototypeof() a trap for object.setprototypeof.
Proxy - JavaScript
function extend(sup, base) { var descriptor = object.getownpropertydescriptor( base.prototype, 'constructor' ); base.prototype = object.create(sup.prototype); var handler = { construct: function(target, args) { var obj = object.create(base.prototype); this.apply(target, obj, args); return obj; }, apply: function(target, that, args) { sup.apply(that, args); base.apply(that, args); } }; var proxy = new proxy(base, handler); descripto...
...r.value = proxy; object.defineproperty(base.prototype, 'constructor', descriptor); return proxy; } var person = function(name) { this.name = name; }; var boy = extend(person, function(name, age) { this.age = age; }); boy.prototype.gender = 'm'; var peter = new boy('peter', 13); console.log(peter.gender); // "m" console.log(peter.name); // "peter" console.log(peter.age); // 13 manipulating dom nodes sometimes you want to toggle the attribute or class name of two different elements.
SharedArrayBuffer - JavaScript
instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array.
... 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.
Symbol.isConcatSpreadable - JavaScript
the symbol.isconcatspreadable well-known symbol is used to configure if an object should be flattened to its array elements when using the array.prototype.concat() method.
... property attributes of symbol.isconcatspreadable writable no enumerable no configurable no examples arrays by default, array.prototype.concat() spreads (flattens) arrays into its result: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] let alphanumeric = alpha.concat(numeric) console.log(alphanumeric) // result: ['a', 'b', 'c', 1, 2, 3] when setting symbol.isconcatspreadable to false, you can disable the default behavior: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] numeric[symbol.isconcatspreadable] = false ...
Symbol.match - JavaScript
this function is called by the string.prototype.match() method.
...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.
Symbol.replace - JavaScript
this function is called by the string.prototype.replace() method.
... for more information, see regexp.prototype[@@replace]() and string.prototype.replace().
Symbol.search - JavaScript
this function is called by the string.prototype.search() method.
... for more information, see regexp.prototype[@@search]() and string.prototype.search().
Symbol.split - JavaScript
this function is called by the string.prototype.split() method.
... for more information, see regexp.prototype[@@split]() and string.prototype.split().
WebAssembly.Memory - JavaScript
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).
Iteration protocols - JavaScript
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.
...alse) } : { done: true } }, _first: true }; }; notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol: console.log([...somestring]); // ["bye"] console.log(somestring + ''); // "hi" iterable examples built-in iterables string, array, typedarray, map, and set are all built-in iterables, because each of their prototype objects implements an @@iterator method.
Lexical grammar - JavaScript
see also string.fromcharcode() and string.prototype.charcodeat().
... see also string.fromcodepoint() and string.prototype.codepointat().
Destructuring assignment - JavaScript
say you want the third element in the array props below, and then you want the 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
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.
with - JavaScript
however, ecmascript 2015 introduces a values property on array.prototype (so that it will be available on every array).
...however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object.
Transitioning to strict mode - JavaScript
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!
... stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via their name or perform a copy of the arguments object using: var args = array.prototype.slice.call(arguments) as the first line of your function this: only use this when it refers to an object you created.
JavaScript
javascript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g.
... advanced inheritance and the prototype chain explanation of the widely misunderstood and under-estimated prototype-based inheritance.
Exported WebAssembly functions - WebAssembly
you can retrieve exported webassembly functions in two ways: by calling table.prototype.get() on an existing table.
... 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.
Content Processes - Archive of obsolete content
accessing the dom the global for the content sandbox has the window object as its prototype.
Modules - Archive of obsolete content
the object it passed to the loadsubscript function is an ordinary object, which has the global object of the loading script as its prototype.
Guides - Archive of obsolete content
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.
dev/panel - Archive of obsolete content
icon: "./my-devtool.png", url: "./my-devtool.html", setup: function(options) { // my setup goes here }, dispose: function() { // my teardown goes here }, onready: function() { // i can send messages to // the panel document here } }); alternatively, you can use the extend function: const { extend } = require("sdk/core/heritage"); function mypanel() {}; mypanel.prototype = extend(panel.prototype, { label: "my panel", tooltip: "...", ....
lang/functional - Archive of obsolete content
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.
Creating Event Targets - Archive of obsolete content
}, onitemvisited: function(aitemid, avisitid, time) { emit(target, "visited", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; bookmarkservice.addobserver(bookmarkobserver, false); } var bookmarkmanager = class({ extends: eventtarget, initialize: function initialize(options) { eventtarget.prototype.initialize.call(this, options); merge(this, options); createobserver(this); } }); exports.bookmarkmanager = bookmarkmanager; the code to interact with the places api is the same here.
Examples and demos from articles - Archive of obsolete content
[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.
JS XPCOM - Archive of obsolete content
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.
LookupNamespaceURI - Archive of obsolete content
addlookupnamespaceuri(doc); addlookupnamespaceuri(element); function addlookupnamespaceuri (type) { if (!type.prototype.lookupnamespaceuri) { type.prototype.lookupnamespaceuri = lookupnamespaceuri; } function lookupnamespaceuri (prefix) { return lookupnamespaceurihelper(this, prefix); } function lookupnamespaceurihelper (node, prefix) { // adapted directly from http://www.w3.org/tr/dom-level-3-core/namespaces-algorithms.html#lookupnamespaceurialgo var i, att, htm...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
the component implementation will include the methods for retrieving the path or file for the extension's home directory: mylocation.prototype = { queryinterface: function(iid) { if (iid.equals(nsisupports)) return this; if (iid.equals(myilocation)) return this; components.returncode = components.results.ns_error_no_interface; return null; }, get locationfile() { return __location__.parent.parent; } } this assumes that the component resides in a subdirectory of the extension director...
Custom about: URLs - Archive of obsolete content
); } createinstance(outer, iid) { if (outer) { throw cr.ns_error_no_aggregation; } return new this.component(); } register() { cm.registerfactory(this.component.classid, this.component.classdescription, this.component.contractid, this); } unregister() { cm.unregisterfactory(this.component.prototype.classid, this); } } instantiation firefox 4+ now in the startup procedure of your bootstrapped addon make sure to do register the factory, for example: let factory; function startup(adata, areason) { // ...
Enhanced Extension Installation - Archive of obsolete content
the model looks something like this: nsextensionsdatasource.prototype = { _composite // the composite that manages the two // datasources at the install locations for // read-only information requests _profileextensions // the rdf/xml datasource for the items at the // profile install location _globalextensions // the rdf/xml datasource for the it...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
i've been manually writing sample code for my own design prototypes for 4 or 5 years now.
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
note: this page documents the jetpack prototype, which is no longer under active development.
Page modifications - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Content - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Extenders - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Twitter - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Libraries - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
First run - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Enabling Experimental Jetpack Features - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Me - Archive of obsolete content
ArchiveMozillaJetpackMetaMe
note: this page documents the jetpack prototype, which is no longer under active development.
Meta - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Jetpack Snippets - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
File access - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Settings - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Simple Storage - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Storage - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Clipboard - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
System information - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
System - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
note: this page documents the jetpack prototype, which has since been replaced by the add-on sdk.
Notifications - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Panel - Archive of obsolete content
ArchiveMozillaJetpackUIPanel
note: this page documents the jetpack prototype, which is no longer under active development.
Selection - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Tabs - Archive of obsolete content
ArchiveMozillaJetpackUITabs
note: this page documents the jetpack prototype, which is no longer under active development.
slideBar - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
UI - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development.
Supporting private browsing mode - Archive of obsolete content
function privatebrowsinglistener() { this.init(); } privatebrowsinglistener.prototype = { _os: null, _inprivatebrowsing: false, // whether we are in private browsing mode _watcher: null, // the watcher object init : function () { this._inited = true; this._os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); this._os.addobserver(this, "private-browsing", false); this._os.
Tamarin build documentation - Archive of obsolete content
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.
The new nsString class implementation (1999) - Archive of obsolete content
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).
Venkman Internals - Archive of obsolete content
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.
Providing Command-Line Options - Archive of obsolete content
* @param aargument an argument to pass to the window (may be null) */ function openwindow(achromeurispec, aargument) { services.ww.openwindow(null, achromeurispec, "_blank", "chrome,menubar,toolbar,status,resizable,dialog=no", aargument); } // command line handler function commandlinehandler() { }; commandlinehandler.prototype = { classdescription: "myapphandler", // changeme: generate a unique id classid: components.id('{2991c315-b871-42cd-b33f-bfee4fcbf682}'), // changeme: change the type in the contractid to be unique to your application contractid: "@mozilla.org/commandlinehandler/general-startup;1?type=myapp", _xpcom_categories: [{ category: "command-line-handler", // changeme: // category ...
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"; } ...
2006-11-24 - Archive of obsolete content
filing bugs for prototype implementations discussions about explicitly address bugs in the prototype implementations.
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
although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean.
E4X for templating - Archive of obsolete content
createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x return h(cond); } else if (_else) { return _else(cond)...
Array.observe() - Archive of obsolete content
changes done via array methods, such as array.prototype.pop() will be reported as "splice" changes.
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
for future-facing usages, consider using array.prototype.map, array.prototype.filter, arrow functions, and spread syntax.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
ecmascript 2016 array.prototype.includes() (firefox 43) typedarray.prototype.includes() (firefox 43) exponentiation operator (firefox 52) ecmascript 2017 object.values() (firefox 47) object.entries() (firefox 47) string.prototype.padstart() (firefox 48) string.prototype.padend() (firefox 48) object.getownpropertydescriptors() (firefox 50) async functions async function (firefox 52) async function expression...
Function.arity - Archive of obsolete content
the arity property used to return the number of arguments expected by the function, however, it no longer exists and has been replaced by the function.prototype.length property.
New in JavaScript 1.5 - Archive of obsolete content
new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word.
New in JavaScript 1.6 - Archive of obsolete content
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
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.
New in JavaScript 1.8 - Archive of obsolete content
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.
ECMAScript 5 support in Mozilla - Archive of obsolete content
added in javascript 1.8.1 (gecko 1.9.1, firefox 3.5) native json support object.getprototypeof() method.
forEach - Archive of obsolete content
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.
Writing JavaScript for XHTML - Archive of obsolete content
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.
Index - Game development
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.
Bounding volume collision detection with THREE.js - Game development
// expand three.js sphere to support collision tests vs box3 // we are creating a vector outside the method scope to // avoid spawning a new instance of vector3 on every check three.sphere.__closest = new three.vector3(); three.sphere.prototype.intersectsbox = function (box) { // get box closest point to sphere center by clamping three.sphere.__closest.set(this.center.x, this.center.y, this.center.z); three.sphere.__closest.clamp(box.min, box.max); var distance = this.center.distancetosquared(three.sphere.__closest); return distance < (this.radius * this.radius); }; demos we have prepared some live demos to demon...
Building up a basic demo with A-Frame - Game development
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.
Building up a basic demo with PlayCanvas editor - Game development
as you can see, the file contains some boilerplate code already: pc.script.create('boxanimation', function (app) { // creates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { // called once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last update update: function (dt) { } }; return boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on ever...
Efficient animation for web games - Game development
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.
Class - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming languages (like javascript) using functions as classes in javascript class-based programming on wikipedia object-oriented programming on wikipedia ...
Inheritance - MDN Web Docs Glossary: Definitions of Web-related terms
learn more learn about it inheritance and the prototype chain ...
OOP - MDN Web Docs Glossary: Definitions of Web-related terms
it follows a prototype-based model (as opposed to class-based).
Parent object - MDN Web Docs Glossary: Definitions of Web-related terms
learn more discussion of inheritance and prototypes in javascript ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Type - MDN Web Docs Glossary: Definitions of Web-related terms
comparison between structured types is not always an easy assumption, as even if the previous data structure is the same, there could be inherited structures inside of the prototype chain.
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
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.
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
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.
Introducing asynchronous JavaScript - Learn web development
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 + '.
Introduction to web APIs - Learn web development
getting a reference to the <canvas> element you want to draw on, and then calling its htmlcanvaselement.getcontext() method: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); anything that we want to do to the canvas is then achieved by calling properties and methods of the context object (which is an instance of canvasrenderingcontext2d), for example: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); }; note: you can see this code in action in our bouncing balls demo (see it running live also).
Solve common problems in your JavaScript code - Learn web development
object-oriented javascript what are object prototypes?
JavaScript object basics - Learn web development
overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
Server-side web frameworks - Learn web development
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.
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.
Componentizing our React app - Learn web development
javascript gives us an array method for transforming data into something else: array.prototype.map().
React interactivity: Events and state - Learn web development
this is a perfect opportunity to use array.prototype.filter().
Starting our Svelte Todo list app - Learn web development
note: you should only disable these warnings if you have good reasons to do so, for example while building a quick prototype.
Creating a Login Manager storage module
const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); function sampleloginmanagerstorage() {} sampleloginmanagerstorage.prototype = { classdescription: "sample nsiloginmanagerstorage implementation", contractid: "@example.com/login-manager/storage/sample;1", classid: components.id("{364a118c-747a-4f6d-ac63-2d2998e5a5c1}"), queryinterface: xpcomutils.generateqi([ci.nsiloginmanagerstorage]), // this registers the category for overriding the built-in nsiloginmanagerstorage _xpcom_categories: [ { category...
Creating Custom Events That Can Pass Data
you can find the prototypes for the function in nsiprivatedomevent.
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
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.
Performance
} object.assign(contentypolicy.prototype, { classdescription: ..., classid: ..., contractid: ..., queryinterface: xpcomutils.generateqi([ci.nsicontentpolicy]), shouldload: function(type, location, origin, context) { let resultlist = services.cpmm.sendsyncmessage("my-addon:check-load", {destination: location, source: origin}) // <=== sync message!
OS.File.Info
determining the owner of a file let promise = os.file.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code.
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
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.
NSPR Poll Method
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.
Optimizing Applications For NSPR
digital unix is the main platform used for nspr's prototype use of ipv6.
NSPR Types
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.
Certificate functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
Cryptography functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
Deprecated SSL functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
Index
189 nss tech notes nss newsgroup: mozilla.dev.tech.crypto 190 nss tech note1 the main non-streaming apis for these two decoders have an identical prototype : 191 nss tech note2 the logger displays all activity between nss and a specified pkcs #11 module.
NSS Memory allocation
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.
NSS_3.12.2_release_notes.html
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.
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 1643528 - fix compilation error with -werror=strict-prototypes.
NSS Developer Tutorial
the function prototype of an exported function, cannot be changed, with these exceptions: a foo * parameter can be changed to const foo *.
nss tech note1
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.
NSS PKCS11 Functions
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.
PKCS 12 functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
PKCS 7 functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
pkfnc.html
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.
SSL functions
the mozilla cross reference (dxr) link for each function provides access to the function definition, prototype definition, and source code references.
S/MIME functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
Utility functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
Scripting Java
javascript strings have methods defined by string.prototype.
Exact Stack Rooting
class fooclass = { "fooprototype", /* name */ jsclass_has_private | jsclass_has_reserved_slots(1), /* flags */ js_propertystub, /* addproperty */ js_propertystub, /* delproperty */ ...
SpiderMonkey Internals
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.
JSExnType
value prototype in javascript jsexn_none an unthrowable error.
JSNewEnumerateOp
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.
JSResolveOp
if not, the process is repeated with obj's prototype.
JS_AlreadyHasOwnProperty
this means that: the prototype chain of obj is not searched.
JS_CheckAccess
it is one of the following values: value description jsacc_proto check for permission to read to obj's prototype.
JS_ClearNonGlobalObject
properties belonging to objects on obj's prototype chain are not affected.
JS_ClearScope
properties belonging to objects on obj's prototype chain are not affected.
JS_DefineObject
proto js::handleobject prototype object to use for the new object, or null.
JS_DeleteElement
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.
JS_DeleteElement2
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.
JS_DeleteProperty
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.
JS_DeleteProperty2
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).
JS_Enumerate
(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.
JS_GetConstructor
to get an object's prototype, use js_getprototype.
JS_GetElement
description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index.
JS_GetOwnPropertyDescriptor
if desc->obj is null, then this property was not found on the prototype chain.
JS_GetParent
objects created by standard library functions, such as array.prototype.concat, have the global object as their parent.
JS_GetProperty
description js_getproperty examines a specified js object obj and its prototype chain for a property with the specified name.
JS_GetPropertyAttributes
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.
JS_GetPropertyDefault
description js_getpropertydefault examines a specified js object obj and its prototype chain for a property with the specified name.
JS_HasElement
description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index.
JS_HasProperty
description js_hasproperty searches an object, obj, and its prototype chain, for a property with the specified name.
JS_IdToProtoKey
description js_idtoprotokey converts a specified js id, id, to a prototype key.
JS_InstanceOf
note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain.
JS_NewGlobalObject
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.
JS_NewPlainObject
description js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]].
JS_NewPropertyIterator
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.
JS_NewScriptObject
a script object has no properties, and its prototype is object.prototype.
JS_ResolveStandardClass
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.
JS_SetAllNonReservedSlotsToUndefined
properties belonging to objects on obj's prototype chain are not affected.
Parser API
node objects by default, reflect.parse() produces node objects, which are plain javascript objects (i.e., their prototype derives from the standard object prototype).
SpiderMonkey 1.8.8
jsclass prototype has changed a number of optional members have been removed from the jsclass prototype.
SpiderMonkey 17
jsclass prototype has changed a number of optional members have been removed from the jsclass prototype.
SpiderMonkey 45
js_setcurrentembeddertimefunction (bug 1159507) js_getcurrentembeddertime (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_hasownpro...
Feed content access API
that code looks like this: feedtestresultlistener.prototype = { handleresult: function(result) { var feed = result.doc; feed.queryinterface(components.interfaces.nsifeed); // open a new window var win = window.open("", "feedtest_window"); var doc = win.document.wrappedjsobject; doc.open(); // write the html header and page title doc.write("<html><head><title>feed: " + feed.title.t...
Generic factory
define a constructor function that matches the constructorprocptr prototype, and call nsigenericfactory::setconstructor with a pointer to that function.
Index
MozillaTechXPCOMIndex
1255 nsgetmoduleproc this function prototype provides the xpcom entry-point into a module.
Components.results
*/ } class.prototype = { /* ...
Components.utils
getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example).
Components.utils.waiveXrays
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.
Components object
utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example).
nsIObserver
function myobserver() { this.register(); } myobserver.prototype = { observe: function(subject, topic, data) { // do your stuff here.
nsIPropertyBag
zid:null mozkeyboard:xpcwrappednative_nohelper mozpay:null mozpermissionsettings:null mozphonenumberservice:phonenumberservice mozpower:mozpowermanager moztcpsocket:null online:true oscpu:"windows nt 5.1" platform:"win32" plugins:pluginarray product:"gecko" productsub:"20100101" useragent:"mozilla/5.0 (windows nt 5.1; rv:30.0) gecko/20100101 firefox/30.0" vendor:"" vendorsub:"" __proto__:navigatorprototype from here we can easily see the operating system version.
nsIRunnable
nsirunnable is generated from nsirunnable.idl here is the prototype of nsirunnable.idl /** * represents a task which can be dispatched to a thread for execution.
nsIScriptError
categories the web console does not display "xpconnect javascript" "component javascript" "chrome javascript" "chrome registration" "xbl" "xbl prototype handler" "xbl content sink" "xbl javascript" "frameconstructor" categories the web console displays "hudconsole" "css parser" "css loader" "content javascript" "dom events" "dom:html" "dom window" "svg" "imagemap" "html" "canvas" "dom3 load" "dom" "malformed-xml" "dom worker javascript" "mixed content blocker" "csp" "invalid hsts headers" "insecure password field" see ...
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
summary this function prototype provides the xpcom entry-point into a module.
XPCOM reference
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.
Setting HTTP request headers
var headername = "x-hello"; var headervalue = "world"; function log(text) { // var consoleservice = components.classes["@mozilla.org/consoleservice;1"].getservice(components.interfaces.nsiconsoleservice); // consoleservice.logstringmessage(text); } function myhttplistener() { } myhttplistener.prototype = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { log("----------------------------> (" + subject + ") mod request"); var httpchannel = subject.queryinterface(components.interfaces.nsihttpchannel); httpchannel.setrequestheader(headername, headervalue, false); return; } if (topic == "profile-aft...
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 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.
DevTools API - Firefox Developer Tools
window.document.body.addeventlistener("click", this.handleclick); } mypanel.prototype = { open: function() { // any asynchronous operations should be done here.
Rich output - Firefox Developer Tools
0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: object { status: "to do", description: "normalize table", datecreated: 1552404533790 } ​ length: 4 ​ <prototype>: array [] debugger eval code:1:9 undefined highlighting and inspecting dom nodes if you hover the mouse over any dom element in the console output, it's highlighted on the page: in the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the inspector with that node selected.
AudioContext.createJavaScriptNode() - Web APIs
example the following script illustrates the use of createjavascriptnode(): var sinewave = function(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: vi...
CSSStyleSheet.insertRule() - Web APIs
ode is a backslash, then isescaped // gets flipped (xor-ed by 1), and if it is not a backslash // then isescaped gets xored by itself, zeroing it isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } // else, there is no unescaped bracket return originalinsertrule.call(this, selectorandrule, "", arguments[2]); }; } })(cssstylesheet.prototype); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.insertrule' in that specification.
CSSUnparsedValue.entries() - Web APIs
the cssunparsedvalue.entries() method 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 - Web APIs
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).
Using the CSS Typed Object Model - Web APIs
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")'.
CSS Typed Object Model API - Web APIs
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).
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('remove')) { return; } object.defineproperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentnode.removechild(this); } }); }); })([element.prototype, characterdata.prototype, documenttype.prototype]); specifications specification status comment domthe definition of 'childnode.remove' in that specification.
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
WebAPIDOMParser
@source https://gist.github.com/1129031 */ /*global document, domparser*/ (function(domparser) { "use strict"; var proto = domparser.prototype, nativeparse = proto.parsefromstring; // firefox/opera/ie throw errors on unsupported types try { // webkit returns null on unsupported types if ((new domparser()).parsefromstring("", "text/html")) { // text/html parsing is natively supported return; } } catch (ex) {} proto.parsefromstring = function(markup, type) { if (/^\s*text\/html\s*(?:;|$)/i.test(type)) { var doc = d...
DOMTokenList.forEach() - Web APIs
<span class="a b c"></span> javascript let span = document.queryselector("span"); let classes = span.classlist; let iterator = classes.values(); classes.foreach( function(value, key, listobj) { span.textcontent += `${value} ${key}/${this} ++ `; }, "arg" ); result polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.domtokenlist && !domtokenlist.prototype.foreach) { domtokenlist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { callback.call(thisarg, this[i], i, this); } }; } specifications specification status comment domthe definition of 'foreach() (as iterable<node>)' in that specification.
DOMTokenList.replace() - Web APIs
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.
Document.registerElement() - Web APIs
optionsoptional an object with properties prototype to base the custom element on, and extends, an existing tag to extend.
DocumentTimeline.DocumentTimeline() - Web APIs
this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeline()' in t...
Element.currentStyle - Web APIs
* 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.
Element.getAttributeNames() - Web APIs
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 ...
Element.hasAttribute() - Web APIs
example var foo = document.getelementbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(name) { return !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes direct...
Element.hasAttributes() - Web APIs
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.
Element.insertAdjacentText() - Web APIs
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 'insertadjacenttex...
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 = {}; ...
IDBKeyRange.includes() - Web APIs
idbkeyrange.prototype.includes = idbkeyrange.prototype.includes || function(key) { var r = this, c; if (r.lower !== undefined) { c = indexeddb.cmp(key, r.lower); if (r.loweropen && c <= 0) return false; if (!r.loweropen && c < 0) return false; } if (r.upper !== undefined) { c = indexeddb.cmp(key, r.upper); if (r.upperopen && c >= 0) return false; if (!r.upperopen && c > 0) return false;...
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).
KeyboardLayoutMap - Web APIs
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).
MSSiteModeEvent - Web APIs
example interface mssitemodeevent extends event { buttonid: number; actionurl: string; } declare var mssitemodeevent: { prototype: mssitemodeevent; new(): mssitemodeevent; } see also microsoft api extensions ...
Node.hasChildNodes() - Web APIs
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 ...
Node.isConnected - Web APIs
WebAPINodeisConnected
*/ 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
instance methods these properties are available only on an instance of the notification object or through its prototype.
OVR_multiview2 - Web APIs
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.
ParentNode.childElementCount - Web APIs
;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.childelementcount == null) { object.defineproperty(constructor.prototype, 'childelementcount', { get: function() { var i = 0, count = 0, node, nodes = this.childnodes; while (node = nodes[i++]) { if (node.nodetype === 1) count++; } return count; } }); } })(window.node || window.element); specification...
StylePropertyMapReadOnly.entries() - Web APIs
the stylepropertymapreadonly.entries() method 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 - Web APIs
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).
Migrating from webkitAudioContext - Web APIs
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...
The structured clone algorithm - Web APIs
the prototype chain is not walked or duplicated.
Window - Web APIs
WebAPIWindow
for overriding the prototype of built-in elements) are listed in a separate section below.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't availab...
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...
Using XMLHttpRequest - Web APIs
for this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, 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...
XMLHttpRequest.sendAsBinary() - Web APIs
/*\ |*| |*| :: 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; } /*...
:scope - CSS: Cascading Style Sheets
WebCSS:scope
javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { return '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></span> </p> result spec...
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
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.
JavaScript data types and data structures - JavaScript
additionally, arrays inherit from array.prototype, which provides to them a handful of convenient methods to manipulate arrays.
Equality comparisons and sameness - JavaScript
there are four equality algorithms in es2015: abstract equality comparison (==) strict equality comparison (===): used by array.prototype.indexof, array.prototype.lastindexof, and case-matching samevaluezero: used by %typedarray% and arraybuffer constructors, as well as map and set operations, and also string.prototype.includes and array.prototype.includes since es2016 samevalue: used in all other places javascript provides three different value-comparison operations: === - strict equality comparison ("strict equality", "identity", "triple equals") == - abstract equality comparison ("loose equality", "double equals") object.is provides samevalue (new in es2015).
Control flow and error handling - JavaScript
// 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.
Grammar and types - JavaScript
enhanced object literals in es2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions.
Unicode property escapes - JavaScript
see also regexp.prototype.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
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.
Memory Management - JavaScript
for instance, a javascript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference).
extends - JavaScript
the .prototype of the extension must be an object or null.
ReferenceError: "x" is not defined - JavaScript
it needs to be some string, so that the string.prototype.substring() method will work.
ReferenceError: reference to undefined property "x" - JavaScript
var foo = {}; foo.bar; // referenceerror: reference to undefined property "bar" valid cases to avoid the error, you need to either add a definition for bar to the object or check for the existence of the bar property before trying to access it; one way to do that is to use the object.prototype.hasownproperty() method), like this: var foo = {}; // define the bar property foo.bar = 'moon'; console.log(foo.bar); // "moon" // test to be sure bar exists before accessing it if (foo.hasownproperty('bar')) { console.log(foo.bar); } ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
"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.
arguments[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the array.prototype.values property.
Rest parameters - JavaScript
from arguments to an array rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments // before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { let normalarray = array.prototype.slice.call(arguments) // -- or -- let normalarray = [].slice.call(arguments) // -- or -- let normalarray = array.from(arguments) let first = normalarray.shift() // ok, gives the first argument let first = arguments.shift() // error (arguments is not a normal array) } // now, you can easily gain access to a normal array using a rest parameter function f(...args) { let normalar...
Array.of() - JavaScript
if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specificat...
Function.length - JavaScript
property of the function prototype object the length property of the function prototype object has a value of 0.
Intl.PluralRules.select() - JavaScript
the intl.pluralrules.prototype.select method returns a string indicating which plural rule to use for locale-aware formatting.
JSON.parse() - JavaScript
var k; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { if (object.prototype.hasownproperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } //...
Math.max() - JavaScript
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.
Object.defineProperties() - JavaScript
polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable.
Object.entries() - JavaScript
(the only important difference is that a for...in loop enumerates properties in the prototype chain as well).
Object.getOwnPropertyDescriptor() - JavaScript
the object.getownpropertydescriptor() method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain).
Object.keys() - JavaScript
polyfill to add compatible object.keys support in older environments that do not natively support it, copy the following snippet: // from /docs/web/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = (function() { 'use strict'; var hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !({ tostring: null }).propertyisenumerable('tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typ...
Object.seal() - JavaScript
the prototype chain remains untouched.
Object.values() - JavaScript
(the only difference is that a for...in loop enumerates properties in the prototype chain as well.) the source for this interactive example is stored in a github repository.
handler.apply() - JavaScript
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.
Reflect.has() - JavaScript
examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties 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 i...
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
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.
TypedArray.from() - JavaScript
this means that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)).
WeakRef - JavaScript
instance methods weakref.prototype.deref() returns the weakref object's target object, or undefined if the target object has been reclaimed.
WebAssembly.Instance - JavaScript
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.
WebAssembly.Table() constructor - JavaScript
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.
class expression - JavaScript
javascript classes use prototype-based inheritance.
typeof - JavaScript
(logical not) operator are equivalent to boolean() // symbols typeof symbol() === 'symbol' typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' // undefined typeof undefined === 'undefined'; typeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful.
yield - JavaScript
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.
class - JavaScript
the class declaration creates a new class with a given name using prototype-based inheritance.
import.meta - JavaScript
the import.meta object is created by the ecmascript implementation, with a null prototype.
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...
Strict mode - JavaScript
ly property var obj2 = { get x() { return 17; } }; obj2.x = 5; // throws a typeerror // assignment to a new property on a non-extensible object var fixed = {}; object.preventextensions(fixed); fixed.newprop = 'ohai'; // throws a typeerror third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect): 'use strict'; delete object.prototype; // throws a typeerror fourth, strict mode prior to gecko 34 requires that all properties named in an object literal be unique.
Trailing commas - JavaScript
when iterating arrays for example with array.prototype.foreach() or array.prototype.map(), array holes are skipped.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
after that, both arrays are merged using the array.prototype.concat() function.
The building blocks of responsive design - Progressive web apps (PWAs)
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.
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
svgexternalresourcesrequired removed never implemented svgelement.viewportelement and svgelement.ownersvgelement nullable implementation status unknown svgelement.getpresentationattribute() removed never implemented (prototype removed in bug 921456) svgcolor and svgicccolor removed never implemented svgelement.focus(), svgelement.blur() not implemented (bug 778654) svgelement.tabindex implemented (bug 778654) document.activeelement implementation status unknown globaleventhandlers on svgelement implementation status unknown options dictionary attribut...
Using custom elements - Web Components
} } 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.