Coding my own function constructor for a string object

I am working through the exercises in the book Object-Oriented JavaScript by Stoyan Stefanov. The exercise is asking me to create a function constructor for a String object. None of the built-in String properties or methods can be used. I am trying to recreate returning a character at a certain index of a string. So the following code is the part of the exercise I am having difficulty getting to work:

var s = new MyString('hello');
s[0];

I cannot figure out how to have my function constructor return the character at the index specified. I should be able to display to the screen the character 'h'. I was able to specifically target certain indexes but that would not be usable as there could be any number of characters in the string passed into the function constructor. Here is the code for that, this return value is for the constructor itself:

return {
    '0': this.string[0]; // Is this code using built-in String object properties or methods?
}

Okay thanks if you can point me in the right direction.

Answers


A simple way to achieve this is to not make it act like a real string, but only deal with the letters that do exist by running over the input string as an array using forEach:

var MyString = function(content) {
  var thisObject = this;
  var letters = content.split('');
  letters.forEach(function(letter, position) {
    thisObject[position] = letter;
  });
};

JS objects are all dynamic property/value maps, so you can set a binding that is effectively this[0] = 't'; this[1] = 'h'; this[2] = 'e' and have something that works.

Does this make sense to do? Not... really? I don't quite see what this exercise teaches you if it's telling you that your code should allow for yourstring[somenumber], but this would be one way to do it.


Need Your Help

JavaScript not writing variable as number (loop)

javascript html for-loop

I have a javascript code like this and this always gives me a problem

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.