Jak określić, czy natywny obiekt JavaScript ma właściwość / metodę?
Myślałem, że to będzie tak proste jak:
if(typeof(Array.push) == 'undefined'){
//not defined, prototype a version of the push method
// Firefox never gets here, but IE/Safari/Chrome/etc. do, even though
// the Array object has a push method!
}
I działa dobrze w Firefoksie, ale nie w IE, Chrome, Safari, Operze, zwracają wszystkie właściwości / metody natywnego obiektu Array jako 'undefined' za pomocą tego testu.
The .metoda hasOwnProperty (prop ) działa tylko na instancjach... więc to nie działa, ale metodą prób i błędów zauważyłem, że to działa.
//this works in Firefox/IE(6,7,8)/Chrome/Safari/Opera
if(typeof(Array().push) == 'undefined'){
//not defined, prototype a version of the push method
}
Czy jest coś złego w używaniu tej składni do określenia, czy istnieje właściwość / metoda na natywnym obiekcie / ~"JavaScript Class"~, czy jest na to lepszy sposób?
4 answers
Po pierwsze, typeof jest operatorem, a nie funkcją, więc nie potrzebujesz nawiasów. Po drugie, dostęp do prototypu obiektu.
alert( typeof Array.prototype.push );
alert( typeof Array.prototype.foo );
Podczas wykonywania typeof Array.push
sprawdzasz, czy obiekt Array ma metodę push, nie jeśli instancje Array mają metodę push.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-27 17:41:08
Właściwy sposób sprawdzenia, czy właściwość istnieje:
if ('property' in objectVar)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-09 08:36:15
.hasOwnProperty
może być dostępny na proptotypie tablicy, jeśli typeof
nie jest wystarczająco idiomatyczny.
if (Array.prototype.hasOwnProperty('push')) {
// Native array has push property
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-01 14:28:51
To tylko przypadek! Generalnie nie można oczekiwać, że metoda prototypu również istnieje w funkcji konstruktora.I działa dobrze w Firefoksie
/ Align = "left" /if(typeof(Array().push) == 'undefined')
new Array().push
, lub [].push
w skrócie, prawidłowo sprawdzi instancję, która ma metodę, o którą prosiłeś.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-16 22:36:53