I have seen this used before but am not sure how to actually implement it. How can a pass a function a variable with this syntax foo.function()
, have foo passed as the input.
Ideally i would like to have it work like this
var foo = 'some string';
var myFunction = function(input){
console.log(input);
}
foo.myFunction();
//should log 'some string'
I got the idea that this is possible from javascript frameworks like jquery where I can have somevar.myFunction()
Also I know that I can extend a pre-defined object but I would like to be able to run this function with any var provided.
What you are looking for is
Object.prototype
. Any object is chained to the Object's prototype chain, ultimately. Which means, in a few words, that whenever an object does not own a property, it will check for it's prototype. The prototype in turn is an object, and so on and so forth.Example:
But, don't start using this until you really know what you're doing, because it's not necessarily good practice to extend a native object's prototype.