Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between property and method with same name

If I have a variable named format and a method with the same name, how would I go about calling the variable, and the method?

use strict;

function Time() {
    this.format = 'x:y:z';
}

Time.prototype = {
    format: function (format) {

    }
}
like image 784
Kid Diamond Avatar asked Mar 17 '23 13:03

Kid Diamond


2 Answers

You can't usually do this, because there is no difference in JavaScript between a method and a property containing a function -- they are exactly the same thing! You create methods by assigning functions to properties.

In this particular case, you can access the function object through the prototype and apply it to the object, but this is a terrible hack.

Time.prototype.format.apply(some_time_object);

You would be better off storing the method and the value in differently-named properties.

like image 98
cdhowie Avatar answered Apr 03 '23 13:04

cdhowie


You cannot do this. The only property which will remain will be the string, the function will not exist in any instantiated objects.

Either name them differently, the method could be formatAs, or have a function with no arguments return the format:

function Time() {
  this.currentformat = 'x:y:z';
}

Time.prototype.format = function (format) {
  if (typeof format === "undefined"){
    return this.currentformat;
  }
  // ...
}
like image 45
theonlygusti Avatar answered Apr 03 '23 14:04

theonlygusti