If you have a constructor function you need to use new
to create the object. You can create an object in the function and return it instead.
(Note though that this is an “anonymous” object, not an instance of capWord
.)
Assigning functions as properties to the function itself doesn’t make much sense. If you only use them inside the function you can just make them regular functions declared locally inside the function.
"use strict";
function capWord(inStr) {
return {
firstIndex: function (inStr) {
document.write(upper(inStr[0]));
space(inStr);
}
};
function space(inStr) {
for (var i = 1; i < inStr.length; i = i + 1) {
document.write(inStr[i]);
if (inStr[i] == " ") {
document.write(upper(inStr[i + 1]));
i = i + 1;
}
}
}
function upper(charUpper) {
return charUpper.toUpperCase();
}
}
var insCapWord = capWord();
insCapWord.firstIndex("learning cool stuff");
As your original code was something that was halfway implemented as a class, I would like to show how it could look implemented fully as a class:
"use strict";
function CapWord(inStr) {
this.str = inStr;
}
CapWord.prototype = {
firstIndex: function() {
document.write(this.upper(this.str[0]));
this.space();
},
space: function() {
for (var i = 1; i < this.str.length; i = i + 1) {
document.write(this.str[i]);
if (this.str[i] == " ") {
document.write(this.upper(this.str[i + 1]));
i = i + 1;
}
}
},
upper: function(charUpper) {
return charUpper.toUpperCase();
}
};
var insCapWord = new CapWord("learning cool stuff");
insCapWord.firstIndex();
8
solved How to avoid the `this` and `new` keywords in Javascript? [closed]