グローバル オブジェクトの文字列化 – デバッグ ヘルパー


【オブジェクトウィンドウ】




Object.prototype.toString.call(this) // '[object Window]'
Object.prototype.toString.call(window) // '[object Window]'
this === window // true



[オブジェクト オブジェクト]




function stringify (x) {
    console.log(Object.prototype.toString.call(x));
}
console.log(stringify({})); // console output: [object Object]
// typeof {} // 'object'


NOTE : [object Object] is most common one . Sometimes it happens then you e.g.:



console.log(`Begin ${object_variable} end.`) 


: object_variable の変数がプリミティブではなくオブジェクトを返す場合、間違いなく [object Object] になります.解決策は、テンプレート リテラルの外で console.log() になります.

console.log(`Begin`, object_variable, `end.`)


: object_variable.some_property に対して some_property が数値や文字列リテラルなどのプリミティブでない限り、上記の最初の場所のようにテンプレート リテラル内に固執できます.


[オブジェクト配列]




typeof [] /* 'object' : technically it's true as everything in JS is an object under the hood , although it limits debugging , a solution to this is : */
function stringify (x) {
    console.log(Object.prototype.toString.call(x));
}
console.log(stringify([])); // console output: [object Array]
// alternatively do so :
Object.prototype.toString.call([]) === '[object Array]' // true
// or simply  :
Array.isArray([]) // true 


NOTE : we use Array.prototype quite often , sometimes we need to check type i.e. double check if it's not an object an we can apply Array.prototype otherwise if e.g. .push() applied upon Object.prototype would end up in an error message of ".push() is not a function" – common sense – you cannot expect otherwise as Object.prototype is not ant Array i.e. it has no idea what a heck is .push() & what it is doing in a wrong world of Object's ..!




[オブジェクト文字列]




// Hereby string presented as object rather than primitive !
Object.prototype.toString.call("" || '' || ``); // [object String]
// e.g.:
Object.prototype.toString.call("" || '' || ``) !== Object.prototype.toString.call(RegExp); // true
// although be careful :
String.prototype.toString.call("food"); // "food"
Object.prototype.toString.call("food"); // [object String]



最も使用頻度の低いオプションは typeof 'function' 、つまり次のようになると思います.

【オブジェクト機能】




// in function declaration form :..
Object.prototype.toString.call(function(){}); // '[object Function]'
typeof function(){} // 'function'
// in function factory form :..
typeof Function // 'function' 
Object.prototype.toString.call(Function); // '[object Function]'
// although be careful as some X.prototype may still be returned as Function if CCCapitalized e.g.:
Object.prototype.toString.call(Object || Array || String || RegExp); '[object Function]'



結論として: ほとんどのプログラミング言語で最も重要なのは、返される型 (デバッグ) または返されると予想される型 (テスト) を知ることです. .今すぐ IDE にジャンプして、コーディングを行い、デバッグを少し行います.これは楽しいことです.