polyfill.js (2077B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 24 var toStringTag = require( './tostringtag.js' ); 25 var toStr = require( './tostring.js' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`. 32 * 33 * @param {*} v - input value 34 * @returns {string} string value indicating a specification defined classification of the input value 35 * 36 * @example 37 * var str = nativeClass( 'a' ); 38 * // returns '[object String]' 39 * 40 * @example 41 * var str = nativeClass( 5 ); 42 * // returns '[object Number]' 43 * 44 * @example 45 * function Beep() { 46 * return this; 47 * } 48 * var str = nativeClass( new Beep() ); 49 * // returns '[object Object]' 50 */ 51 function nativeClass( v ) { 52 var isOwn; 53 var tag; 54 var out; 55 56 if ( v === null || v === void 0 ) { 57 return toStr.call( v ); 58 } 59 tag = v[ toStringTag ]; 60 isOwn = hasOwnProp( v, toStringTag ); 61 62 // Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`. 63 try { 64 v[ toStringTag ] = void 0; 65 } catch ( err ) { // eslint-disable-line no-unused-vars 66 return toStr.call( v ); 67 } 68 out = toStr.call( v ); 69 70 if ( isOwn ) { 71 v[ toStringTag ] = tag; 72 } else { 73 delete v[ toStringTag ]; 74 } 75 return out; 76 } 77 78 79 // EXPORTS // 80 81 module.exports = nativeClass;