0

What I want to do should be incredibly simple but I suppose I'm not understanding the basic concepts and causing me more confusion than I'd like to admit.

I want to pass a value into a function by "chaining" it instead of passing the value as an argument.

I want to be able to do this:

var formattedDate = myDate.convertTime()

Instead of:

var formattedDate = convertTime(myDate);

In my search I've come across many examples of how to use call functions inside objects, but they always start with declaring a new object and calling the function inside that object that simply updates predefined variables like age, name, or location as in new Obj(name, age) which doesn't seem to be what I am looking for when applied to my situation. I'd really appreciate some guidance in the right direction.

Err
  • 890
  • 2
  • 11
  • 32

2 Answers2

1

Are you looking for something like following

String.prototype.myFunction = function() {
    return this.toUpperCase();
}

var text = "sample text";

console.log(text.myFunction()); // calling user defined function 

Fiddle: https://jsfiddle.net/mna7jxrs/

Update 1:

For example, We're passing a date string to convertTime() and it is converting it to UTC String

Date.prototype.convertTime = function() {
    return this.toUTCString();
}

var date = new Date();

console.log(date); // Mon Oct 31 2016 11:56:57 GMT+0530 (India Standard Time)

console.log(date.convertTime()); // Mon, 31 Oct 2016 06:26:57 GMT

Fiddle: https://jsfiddle.net/doc7gL2g/

Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
1

What you want to do is add a method to your object myDate.

Lets assume myDate is a date created by var myDate = new Date();.

If you want to add it only to the current object, you can do this way:

var myDate=new Date();

myDate.convertTime = function() {
   console.log("I’m working on", this);
};

myDate.convertTime(); // -> see console

Now to make it more generic, you want to do something we call monkey patching:

Date.prototype.convertTime = function() {
  console.log("I’m working on", this);
};

var myDate = new Date();
myDate.convertTime(); // -> see console

var myOtherDate = new Date();
myOtherDate.convertTime(); // -> see console

A working pen for the monkey patch: http://codepen.io/BuonOmo/pen/RGzYmz?editors=0012

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82