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) {
}
}
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.
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;
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With