Discover what methods javascript object has - javascript

I have a page that renders just fine. On the page is a control and I wanted to set the visibility to hidden. I can get a handle on the object just fine but then when I went to use what I thought were pretty typical methods such as:
.setVisible(false);
or
.css("visibility", "hidden");
I got the object doesn't support method error.
Now to solve my visibility problem there was a containing div for the control so I just set the div to hidden.
$('#footer_statecode').hide();
My question however for the future is how would I discover the methods supported by an object.
My google searches came close such as this SO post but in these example the person had a specific method they were looking for. I am interested in seeing everything available....and it doesn't have to be via an alert(); I'd be just fine using some capability in the different browsers Developer tools (F12).
Thank you once again for sharing your knowledge.

You can use this. It won't include built-in JavaScript methods (ex Array.prototype.push)
var methods = [];
for (var prop in object) {
if (typeof object[prop] === "function") {
methods.push(prop);
}
}

You can find it like this:
function getMethods(prop)
{
var res = [];
for(var prop in x) {
if(typeof x[prop] == 'function') {
res.push(prop);
}
}
return res;
}
You can also look at the Object.prototype.hasOwnProperty()

Related

Getter functions

I've peeked into many plugins' code (for educational purposes) and basically every one of them (which deals with prototypes), has bunch of functions like this:
myMarker.prototype.getPosition = function() {
return this.latlng;
};
//OR
myMarker.prototype.getObject = function() {
return this;
};
What's the reason behind this?
Why not just to use someObject.latlng instead of someObject.getPosition()?
One common reason for doing this is to avoid coupling the object's internal data storage to the API; in this example you could change the way the position is stored internally, and then add some processing to getPosition() to return a backwards compatible result.
For example, version 1.1 of this library might look like this, and calling code wouldn't need to be changed:
myMarker.prototype.getPosition = function() {
return this.latitude + this.longitude;
};
It is possible to accomplish this using computed properties with ES5 get and set, but only if the code doesn't need to run on Internet Explorer 8 and below.
When you say like this.
myMarker.prototype.getPosition = function() {
return this.latlng;
};
You are defining function getPosition which available to all instance to class myMarker.
So,all object of this class share this method without replication.
For someObject.latlng,there is nothing wrong.
But assume, this object is accessible to all which are in the current scope.So,it can be modified/accessible to anyone.
When you go through prototype you are trying to define some pattern,which gives restriction for access and modification of property

Display where function is called from not where it is defined console javascript

I am a lazy developer... I like to make shortcuts, so I bound console.info to c
/*core_functions.js*/
/*==================================================
Bind C to be alert on mobile console.log in desktop
================================================== */
window.c = false;
if (typeof console === "object" && typeof console.error === "function" && !SP.isMobile) {
c = function (msg) {
console.info(msg);
};
} else {
c = function (msg) {
debug(msg);
};
}
/*somefile.js*/
c(anObject);
I have been using this for quite some time and something has always annoyed me. It displays the file in which the function is defined rather than where the function is called from:
core_functions.js:40 Object {stadiumname: "Stadium 3", pitch: Object, lights: Object, seats: Object, scoreboards: Object…}
Can I reference where the function is being called from? Or am I forever stuck with this minor annoyance?
You are seeing that line number because it really is where console.info is called. A way I can think to avoid that is by calling the real console method rather than proxying with an intermediate function.
It seems to me you want to have an abstraction layer to handle your logging using the native console or a custom one.
In that case you could try something like this:
var c = (typeof console === 'object') ? console : alternative;
And then use it as:
c.log('Hello World');
That way your alternative object could be one with the methods you are considering on using, for instance:
var alternative = {
log: function() {
window.alert.apply(window, arguments);
}
};
This way you won't get your c() function but, I think, you'll end up with a more flexible solution. By exposing the same interface that console has you could even add these logging facilities to any code running in your app (that is, 3rd party code using native console)
window.console = (typeof window.console === 'object') ? window.console : alternative
or if you are feeling very lazy that day :)
window.console = window.console || alternative
This is no perfect technique at all but if you are only using it while developing it might help.
Also, I never really participate in Stack Overflow so I'm very sorry if I'm ignoring any rule or etiquette :)
I use the following to get backtraces, you might be able to do something with it.
arguments.callee.caller.toString()

Which modules of mootools more I am using?

All mootools more modules are included in my app, but I would like to remove the ones I am not using. Is there a quick way to know which modules I am using starting from the script depending on mootools more?
no easy way, I am afraid. you can spy on stuff while your app runs so you can get some usage/coverage stats but because mootools is prototypal, the extensions to Array/String/Function/Date etc that more does may be more complicated to catch.
To catch classes that have been instantiated, build a list and use something like that:
Object.monitor = function(obj, match){
var keys = (function(obj){
// include from prototype also, any function.
var keys = [], key;
for (key in obj) typeof obj[key] === 'function' && keys.push(key);
return keys;
}(obj)),
log = function(what, method){
// more use goes red in console.
console.log(obj, method, what);
},
counters = {};
keys.forEach(function(key){
var orig = obj[key];
Object.defineProperty(obj, key, {
get: function(){
key in counters || (counters[key] = 0);
counters[key]++;
key.test(match) && log(counters[key], key);
return orig;
}
});
});
};
var protos = [Fx.Reveal, Fx.Slide, Request.JSONP]; // etc etc - stuff you are unsure of.
protos.forEach(function(klass){
Object.monitor(klass.prototype, /\$constructor/);
});
new Request.JSONP({});
as soon as any of these items gets instantiated OR extended, the constructor will get referenced and you will get the log to show it. http://jsfiddle.net/dimitar/8nCe6/ - this will instantiate Request.JSONP().
I wrote the Object.monitor to spy on methods being called on a particular instance but the same principle applies. The console formatting only works nice in FireBug and WebInspector - native FF console needs to be made simple.
http://fragged.org/spy-on-any-method-on-an-object-and-profile-number-of-times-called_1661.html
you can use it to spy on say, Array.prototype or any suchlike as well - but the difficulty is the code complexity of more. Hard to really nail it down :(
probably easier to concatenate all your scripts EXCEPT for mootools-more then grep for known classes / methods from the Types.
Did you compress the file?
If you haven't removed the original comments from your build, there should be a link at the top of your file with a list of the included packages and a link. e.g.
// Load this file's selection again by visiting: http://mootools.net/more/065f2f092ece4e3b32bb5214464cf926
If you don't have the link, but other comments are included, search the file for script: and you should get a list back of all the included packages.

how to find all usages of jQuery or Zepto in your code

My team and I want to maintain a low cost for switching from Zepto to another framework or native browser calls (we only target WebKit) while using it.
What are the tactics of keeping track of the places in the code where Zepto is used?
Is there anything better that maintaining a Readme list of methods used?
How would you do it?
jQuery: You can use noConflict to assign some nice, unique name to the jQuery function (perhaps jQuery itself as that's built-in, but if that's a pain something else readily distinguished from other things, like $jq or some such — noConflict returns the jQuery function so you can do that, e.g. var $jq = jQuery.noConflict();).
Zepto: Despite claiming a "jQuery-compatible syntax," it doesn't appear to support noConflict per se. However, it looks like if $ is already defined on the window object, it will leave it alone, because of this line:
'$' in window || (window.$ = Zepto);
So define $ before loading Zepto and then only use Zepto in your code (or assign something to it that's equally unique, like $jq or $zt, etc. — e.g., var $zt = Zepto;).
In either case: Then search your code for those if/when you need to find those bits.
Beyond searching for $ and specific methods, you could identify which methods are in use by logging their usage in running code.
The following code will log the function used and the stack trace every time you make a jQuery call but not log any internal calls made by jQuery.
<script>
(function(){
var insideJQuery = false;
function replaceMethod(obj, method, prefix) {
var oldMethod = obj[method];
if(typeof oldMethod !== "function")
return;
obj[method] = function() {
var externalCall = !insideJQuery;
insideJQuery = true;
var output = oldMethod.apply(this, arguments);
if(externalCall) {
console.log(prefix + method + ' called');
console.trace();
insideJQuery = false;
}
return output;
}
}
for(var method in $.fn) {
if(method != 'constructor' &&
method != 'init')
replaceMethod($.fn, method, '$.fn.');
}
for(var method in $) {
if(method != 'Event')
replaceMethod($, method, '$.');
}
})();
</script>
The exception of course would be jQuery calls inside jQuery calls like $(document).ready(function(){$('div')});.
Um, you could search for the $ sign?
Every method like parents() will be called on something that was ultimately created with the $ sign. So if you find all instances of $ and trace the use of the resulting variables you'll have everything.

What version of IE uses window[objectName] instead of window.document[objectName]?

I am trying to use a Javascript callback to a Flex application embedded in my page. Looking through some examples, I've seen this code used to get a reference to the Flex application:
// Get the reference:
function thisFlexApp(appName) {
if(navigator.appName.indexOf ('Microsoft') != -1) {
return window[appName];
}
else {
return window.document[appName];
}
}
// Use it:
var someVariable = thisFlexApp('NameOfFlexApp').callbackMethod();
I used that method, but using IE9 I got errors indicating the "thisFlexApp" call didn't work. Turns out that window.document[appName] worked in IE9, but window[appName] didn't. Since I don't expect my government clients to be using IE9 yet, I'm wondering what version of IE this method would actually work on? Is there another test that would be better to use instead of the one above which just assumes all versions of IE work a certain way? Thanks in advance.
Don't check the browser version, check the browser's capabilities. You can just check if window[appName] exists, and if it does, use it.
function thisFlexApp(appName) {
if(window[appName]) {
return window[appName];
}
else {
return window.document[appName];
}
}
Or even shorter:
function thisFlexApp(appName) {
return window[appName] || window.document[appName];
}

Categories