Kid Diamond
Kid Diamond

Reputation: 2301

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) {

    }
}

Upvotes: 5

Views: 5857

Answers (3)

user3310334
user3310334

Reputation:

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;
  }
  // ...
}

Upvotes: 2

Domino
Domino

Reputation: 6768

Functions are actually objects stored in properties in JavaScript, so that's not possible.

When you call instance.format(), the interpreter looks at the instance to see if it has a property called format. If there is, it checks if it's a function and throws an error if it isn't. If the instance doesn't have such a property, it checks the instance's prototype and does the same thing, until an ancestor has a format property or until it reaches the top of the inheritance tree. In your situation, it will always try to execute the string, which will cause an error. The interpreter never looks at the prototype for its format() method.

You could rename the property to formatString or mask if you prefer.

Upvotes: 1

cdhowie
cdhowie

Reputation: 168988

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.

Upvotes: 7

Related Questions