phpjs
Version:
74 lines (63 loc) • 2.53 kB
Markdown
layout: page
title: "JavaScript property_exists function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/property_exists:495
- /functions/view/property_exists
- /functions/view/495
- /functions/property_exists:495
- /functions/495
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's property_exists
{% codeblock classobj/property_exists.js lang:js https://raw.github.com/kvz/phpjs/master/functions/classobj/property_exists.js raw on github %}
function property_exists (cls, prop) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// * example 1: function class_a () {this.prop1 = 'one'};
// * example 1: var instance_a = new class_a();
// * example 1: property_exists(instance_a, 'prop1');
// * returns 1: true
// * example 2: function class_a () {this.prop1 = 'one'};
// * example 2: var instance_a = new class_a();
// * example 2: property_exists(instance_a, 'prop2');
// * returns 2: false
cls = (typeof cls === 'string') ? this.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');
}
{% endcodeblock %}
- [view on github](https://github.com/kvz/phpjs/blob/master/functions/classobj/property_exists.js)
- [edit on github](https://github.com/kvz/phpjs/edit/master/functions/classobj/property_exists.js)
### Example 1
This code
{% codeblock lang:js example %}
function class_a () {this.prop1 = 'one'};
var instance_a = new class_a();
property_exists(instance_a, 'prop1');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}
### Example 2
This code
{% codeblock lang:js example %}
function class_a () {this.prop1 = 'one'};
var instance_a = new class_a();
property_exists(instance_a, 'prop2');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
false
{% endcodeblock %}
### Other PHP functions in the classobj extension
{% render_partial _includes/custom/classobj.html %}