How to call a function and pass a variable with period notation

270 views Asked by At

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.

2

There are 2 answers

2
Gerard van Helden On BEST ANSWER

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:

Object.prototype.foo = function () {
    return "bar";
}

console.log("a string is an object".foo());

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.

0
jwatts1980 On

I'm not exactly sure what you mean. But given an example custom type in JavaScript:

function SomeType() {
    this.someVar = null;
    this.newFunction = function() {
        //do something, for example:
        this.someVar = "Hello World!";
    };
}

var foo = new SomeType();
foo.newFunction();
alert(foo.someVar);

Inside newFunction(), using the this identifier refers to the instance foo. So if inside newFunction you write:

this.someVar = "Hello World!";

Then foo.someVar will equal "Hello World!". So foo is not passed as an input but is inherently accessible using this.