1.0.6 • Published 7 years ago
@kingjs/property-descriptor.target-instance-of v1.0.6
@kingjs/property-descriptor.target-instance-of
Add a precondition to an accessor or function descriptor which throws unless this at runtime is an instanceof a specific type.
Usage
var assert = require('assert')
var targetInstanceOf = require('@kingjs/property-descriptor.target-instance-of');
/**
* @this String The string to capitalize.
*
* @returns A capitalized version of @this.
*/
function capitalize() {
var firstChar = this.charAt(0);
// capitalize
firstChar = firstChar.toUpperCase();
var result = firstChar + this.substring(1, this.length);
return result;
}
// use a symbol instead of a name so as not to pollute builtin
// types with properties that may collied with other frameworks
var Capitalize = Symbol(capitalize.name);
// extend String with capitalize
Object.defineProperty(
Object.prototype,
Capitalize,
targetInstanceOf.call(
{ value: capitalize },
() => String,
Capitalize
)
);
// call capitalize on a string
var test = 'foobar'[Capitalize]();
assert(test == 'Foobar');
// note that capitalize has been added to String.prototype (even
// though we originally defined capitalize on Object.prototype).
var descriptor = Object.getOwnPropertyDescriptor(String.prototype, Capitalize);
assert(descriptor.value == capitalize);
// cannot capitalize an array! The stub has detected the type of
// `this`, being an `Array`, is not an instanceof `String` and so
// throws. Its derivation by restriction!
assert.throws(() => [][Capitalize]());API
targetInstanceOf(this, callback(parameters)[, name])Parameters
this: A descriptor describing an accessor or function.callback: Returns the typethismust be aninstanceofat runtime in order to access the property.name: The name of the property being described. If provided,thisdescriptor will be declared on the deepest prototype of the runtimethisfor which isinstanceofreturns true.
Returns
A descriptor whose accessors or function throws at runtime unless this at runtime is an instanceof the type return by callback.
Install
With npm installed, run
$ npm install @kingjs/property-descriptor.target-instance-ofSource
https://repository.kingjs.net/property-descriptor/target-instance-of
License
MIT