javascript ですべてのユーザー定義のウィンドウ プロパティと変数 (グローバル変数) を見つける方法はありますか?
試してみconsole.log(window)
ましたが、リストは無限です。
javascript ですべてのユーザー定義のウィンドウ プロパティと変数 (グローバル変数) を見つける方法はありますか?
試してみconsole.log(window)
ましたが、リストは無限です。
実行時にスナップショットを作成して比較する代わりに、ウィンドウをクリーン バージョンのウィンドウと比較することもできます。これをコンソールで実行しましたが、関数に変えることができます。
// make sure it doesn't count my own properties
(function () {
var results, currentWindow,
// create an iframe and append to body to load a clean window object
iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
// get the current list of properties on window
currentWindow = Object.getOwnPropertyNames(window);
// filter the list against the properties that exist in the clean window
results = currentWindow.filter(function(prop) {
return !iframe.contentWindow.hasOwnProperty(prop);
});
// log an array of properties that are different
console.log(results);
document.body.removeChild(iframe);
}());
自分で作業を行う必要があります。できるだけ早く、すべてのプロパティを読み込みます。その時点から、プロパティ リストを静的リストと比較できます。
var globalProps = [ ];
function readGlobalProps() {
globalProps = Object.getOwnPropertyNames( window );
}
function findNewEntries() {
var currentPropList = Object.getOwnPropertyNames( window );
return currentPropList.filter( findDuplicate );
function findDuplicate( propName ) {
return globalProps.indexOf( propName ) === -1;
}
}
だから今、私たちは次のように行くことができます
// on init
readGlobalProps(); // store current properties on global object
以降
window.foobar = 42;
findNewEntries(); // returns an array of new properties, in this case ['foobar']
もちろん、ここで注意しなければならないのは、グローバル プロパティ リストを「フリーズ」できるのは、スクリプトが最も早い時点でグローバル プロパティ リストを呼び出すことができるときだけであるということです。
多分これ?:
for (var property in window)
{
if (window.hasOwnProperty(property))
console.log(property)
}