JavaScript function_exists
Checks if the function exists
1 2 3 4 56 7 8 9 1011 12 13 14 1516 | function function_exists (function_name) { // Checks if the function exists // // version: 1008.1718 // discuss at: http://phpjs.org/functions/function_exists // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Steve Clay // + improved by: Legaev Andrey // * example 1: function_exists('isFinite'); // * returns 1: true if (typeof function_name == 'string'){ return (typeof this.window[function_name] == 'function'); } else{ return (function_name instanceof Function); }} |
Examples
Running
1 | function_exists('isFinite'); |
Should return
1 | true |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have function_exists goodness in JavaScript.
Added one last condition which will find if there is a static members on the class to which an object belongs, as well as some example tests for it as well:
[CODE="Javascript"]myClass2.prototype.instanceMethod = function () {}
myClass2.prototype.mine = 'my member';
var_dump(property_exists(new myClass2, 'mine')); //true
var_dump(property_exists(new myClass2, 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists(new myClass2, 'bar')); //false
var_dump(property_exists(new myClass2, 'staticProp')); //true, as of PHP 5.3.0
var_dump(property_exists(new myClass2, 'staticMethod')); //false
var_dump(property_exists(new myClass2, 'instanceMethod')); //false
var myclass2 = new myClass2();
myclass2.staticMethod(); // doesn't exist
[/CODE]
[CODE="Javascript"]function property_exists (cls, prop) {
cls = (typeof cls === 'string') ? window[cls] : cls;
if (typeof cls === 'function' && cls.toSource && cls.toSource().match(new RegExp('this\\.'+prop+'\\s'))) { // Hackish and non-standard but can probably detect if setting the property (we don't want to test by instantiating as that may have side-effects)
return true;
}
return (cls[prop] !== undefined && typeof cls[prop] !== 'function') || (cls.prototype !== undefined && cls.prototype[prop] !== undefined && typeof cls.prototype[prop] !== 'function') || cls.constructor && cls.constructor[prop] !== undefined && typeof cls.constructor[prop] !== 'function';
}[/CODE]
And here's one for property_exists(), based on PHP doc examples:
[CODE="Javascript"]var myClass = {
mine : {},
xpto : {},
test : function () {
var_dump(property_exists('myClass', 'xpto')); // true
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); // false (PHP considers methods as distinct from properties)
myClass.test(); // true
function myClass2 () {
this.xpto = 'something';
}
myClass2.staticProp = 'staticValue';
myClass2.staticMethod = function () {
var_dump(property_exists('myClass2', 'xpto')); // true
}
myClass2.prototype.instanceMethod = function () {}
myClass2.prototype.mine = 'my member';
var_dump(property_exists('myClass2', 'mine')); //true
var_dump(property_exists(new myClass2, 'mine')); //true
var_dump(property_exists('myClass2', 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass2', 'bar')); //false
var_dump(property_exists('myClass2', 'staticProp')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass2', 'staticMethod')); //false
var_dump(property_exists('myClass2', 'instanceMethod')); //false
myClass2.staticMethod(); // true
function property_exists (cls, prop) {
cls = (typeof cls === 'string') ? window[cls] : cls;
if (typeof cls === 'function' && cls.toSource && cls.toSource().match(new RegExp('this\\.'+prop+'\\s'))) { // Hackish and non-standard but can probably detect if setting the property (we don't want to test by instantiating as that may have side-effects)
return true;
}
return (cls[prop] !== undefined && typeof cls[prop] !== 'function') || (cls.prototype !== undefined && cls.prototype[prop] !== undefined && typeof cls.prototype[prop] !== 'function');
}
[/CODE]
Here's a slightly hackish and partially non-standard way to get class_exists(). Of course, any function can be instantiated in JavaScript, but I've attempted to do a hopefully more sophisticated checking to see whether it was designed as one.
[CODE="Javascript"]
function A (z) {this.z=z}
alert(class_exists('A')); // true (constructor sets 'this')
var a = new A('str');
alert(class_exists('a')); // false (objects not classes)
function B () {}
B.c = function () {}; // Add a static method, making it a class
alert(class_exists('B')); // true
function C () {}
C.prototype.z = function () {};
alert(class_exists('C')); // true
function D (b) {}
alert(class_exists('D')); // false (seems like a regular function)
var e = {
E : function (z) {this.z=z;}
}
alert(class_exists('e.E')); // false (the 'this' refers to containing object, not to an instance property)
function class_exists (cls) {
cls = window[cls]; // Note: will prevent inner classes
if (typeof cls !== 'function') {return false;}
for (var i in cls.prototype) {
return true;
}
for (var i in cls) { // If static members exist, then consider a "class"
if (i !== 'prototype') {
return true;
}
}
if (cls.toSource && cls.toSource().match(/this\./)) { // Hackish and non-standard but can probably detect if setting a property (we don't want to test by instantiating as that may have side-effects)
return true;
}
return false;
}[/CODE]
Fixing an error and adding more examples:
[CODE="Javascript"]function Directory () {}
Directory.test = function () {}
Directory.prototype.read = function () {}
$directory = new Directory('.');
alert(true === method_exists($directory,'read')); // true
alert(true === method_exists($directory,'write')); // false
alert(true === method_exists('Directory','test')); // true
alert(true === method_exists('Directory','read')); // false
alert(true === method_exists($directory,'test')); // false
function method_exists (obj, method) {
if (typeof obj === 'string') {
return window[obj] && typeof window[obj][method] === 'function'
}
return typeof obj[method] === 'function';
}
[/CODE]
Sorry, neglected to see a string was allowable to test for a static method:
[CODE="Javascript"]
function Directory () {}
Directory.test = function () {}
Directory.prototype.read = function () {}
$directory = new Directory('.');
alert(true === method_exists($directory,'read')); // true
alert(true === method_exists($directory,'write')); // false
alert(true === method_exists('Directory','test')); // true
[/CODE]
[CODE="Javascript"]function method_exists (obj, method) {
if (typeof obj === 'string') {
return typeof window[obj][method] === 'function'
}
return typeof obj[method] === 'function';
}[/CODE]
Here's another one more related to the function here...
Sample based on PHP manual...
[CODE="Javascript"]function Directory () {}
Directory.prototype.read = function () {}
$directory = new Directory('.');
alert(true === method_exists($directory,'read')); // true
alert(true === method_exists($directory,'write')); // false
[/CODE]
[CODE="Javascript"]function method_exists (obj, method) {
return typeof obj[method] === 'function';
}[/CODE]
@ Brett Zamir: get_defined_functions... I must say, sometimes I'm really surprised what you guys come up with :) But it works! I have even hacked a testcase around it. Thanks again.
Here's one more...
[CODE="Javascript"]
function get_defined_functions() {
var arr = [];
for (var i in window) {
try {
if (typeof window[i] === 'function') {
arr.push(window[i].name);
}
}
catch (e) {
}
}
return arr;
}
alert(get_defined_functions());[/CODE]
@ Andrea Giammarchi: Wow you did some impressive work that I was unaware of. Cool :) I will look into the define function later today and add it here, thanks a lot for that.
About the PHP vs JS stuff.. I'm not trying to port or emulate the entire language or control structures of PHP. Indeed I don't see the need because (and this is quite a statement), Javascript seems to have more elegant features in that category anyway.
However in my eyes, PHP does provide a large set of standard functions that make developing very easy, and some of them don't have good standard Javascript implementations, though they often would be great to have client-side.
So in this project by also providing the functions separately, I hope to keep people from inventing the wheel and give them a head start.
Thanks for your comment Andrea, well appreciated. And respect for your Overbyte editor & JHP environment. The idea is very interesting, and I can see it's all coded with very high skill.
If you are interested in some similar stuff, looks for JHP setting in overbyte editor.
Finally, You could use my define function too, that accept only scalar values as PHP and is compatible with IE, FireFox, Safari and Opera (Opera devs will fix soon their const keyword ... I guess ...)
http://webreflection.blogspot.com/2007/10/cow-javascript-define-php-like-function.html
However, nice stuff .. not so useful in my mind because of different languages nature (I would like to have JS behaviours in PHP, for example :D) but good luck for the project
@ Legaev Andrey: Hi, I've updated the function and changed your name. I wasn't sure you really want me to enlist your email address?
Sorry for my short previous comment and my bad English. Below full version.
If we pass function_name as String then all ok. But if we pass the link to function (link to Object-function) then
this function returns false. In my opinion in this case this function should return true when first
parameter is instance of Function.
function function_exists_new( function_name ) {
if (typeof function_name == \'string\')
return (typeof window[function_name] == \'function\');
else
return (function_name instanceof Function);
}
P.S. Please, change my name to Legaev Andrey <legaev_andrey@mail.ru>. Thanks.
@ Steve Clay & Andrey: Thanks You guys I've updated the function. I left the old code in the comments for future reference.


Kevin van Zonneveld
30 Dec '08
Seriously though: I think the class_exists example I've made should return true, but it doesn't. That's a good one to start with.