Functions don't have a method
property, which is why you're getting undefined
. You may be thinking of an extension to functions that Douglas Crockford likes to use, which looks like this:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
But that's not part of JavaScript, it's a Crockford thing. You'd have to have that code in your code and execute it before you do your thing in order to use it.
As you can see, it does virtually nothing; it's the smallest bit of syntactic sugar. To create your setValue
method without it, for instance, you'd do this:
Parenizor.prototype.setValue = function(value) {
this.value = value;
return this;
};
If you don't want to use Crockford's method
function, just do that instead.
Side note: You're falling prey to The Horror of Implicit Globals; you need to declare your myParenizor
and myString
variables.
Live example of defining Crockford's method
before using it (and declaring the variables):
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
function Parenizor(value) {
this.setValue(value);
}
Parenizor.method('setValue', function(value) {
this.value = value;
return this;
});
Parenizor.method('getValue', function() {
return this.value;
});
Parenizor.method('toString', function() {
return '(' + this.getValue() + ')';
});
var myParenizor = new Parenizor(0);
var myString = myParenizor.toString();
snippet.log(JSON.stringify(myParenizor));
snippet.log(myString);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>