Skip to content

Instantly share code, notes, and snippets.

@FokkeZB
Last active November 5, 2015 17:15
Show Gist options
  • Select an option

  • Save FokkeZB/08165210d279766ef67c to your computer and use it in GitHub Desktop.

Select an option

Save FokkeZB/08165210d279766ef67c to your computer and use it in GitHub Desktop.
Checking for Titanium API objects
var jsObject = {
foo: 'bar'
};
var tiObject = Ti.UI.create2DMatrix();
function isJsObject(obj) {
return typeof obj.__proto__ !== 'undefined';
}
console.log('jsObject: ' + (isJsObject(jsObject) ? 'yes' : 'no'));
console.log('tiObject: ' + (isJsObject(tiObject) ? 'yes' : 'no'));
@skypanther

Copy link
Copy Markdown

Nice technique. Minor typos in isJsObject(jtibject) should be

console.log('tiObject: ' + (isJsObject(tiObject) ? 'yes' : 'no'));

@yuchi

yuchi commented Sep 19, 2014

Copy link
Copy Markdown

Did you mean __proto__?

@FokkeZB

FokkeZB commented Sep 22, 2014

Copy link
Copy Markdown
Author

Indeed @yuchi, thx!

@FokkeZB

FokkeZB commented Sep 22, 2014

Copy link
Copy Markdown
Author

Updated the above and tested in Triple:

> isJsObject(Object.create(null));
true
> isJsObject({});
true
> isJsObject([]);
true
> isJsObject('');
true
> isJsObject(Ti.UI.createWindow());
false
> isJsObject(Ti.UI.create2DMatrix);
false
> isJsObject(new Object());
true
> isJsObject(new Date());
true
> isJsObject(function() {});
true

@yuchi

yuchi commented Sep 22, 2014

Copy link
Copy Markdown

Oh gosh:

console.log(Object.create(null)._proto__ === undefined); // true
console.log(Object.create(null)._proto__ === null); // false
console.log(typeof Object.create(null)._proto__); // "undefined"

var temp = Object.create(null)._proto__;
console.log(temp === undefined); // false, WAT?
console.log(temp === null); // true, WAT?!?!!
console.log(typeof temp); // "object"

@FokkeZB

FokkeZB commented Sep 22, 2014

Copy link
Copy Markdown
Author

Strange indeed, but:

> var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; };
undefined
> _isObject(Object.create(null).__proto__);
false
> var temp = Object.create(null).__proto__; _isObject(temp);
false

@FokkeZB

FokkeZB commented Sep 22, 2014

Copy link
Copy Markdown
Author

I guess as long as you know you have an object and need to test if it's not a Ti one... the code as I have it now works ok ;)

@yuchi

yuchi commented Sep 22, 2014

Copy link
Copy Markdown

Looks like that as an expression (or part of one) it returns undefined, but when passed around (assignment, or function invocation) is null.

@yuchi

yuchi commented Sep 22, 2014

Copy link
Copy Markdown

I feel stupid. _proto__ with one _

@yuchi

yuchi commented Sep 22, 2014

Copy link
Copy Markdown
function isJSObject(o) { return !!(o && o.__proto__ !== undefined); };

works flawlessy…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment