-1

I was wondering how to write a method prefixed by . as in .join() [for arrays] such that for any [string-type] variable I had I could do

var myString.editAt(index)

without having to take the annoying and visually jarring editAt(myString,index).

In looking up answers to this (I don't know exactly how to phrase it which doesn't help me in my search) all I've found are what appear to be specific (?) ways to refer to objects - that is, ones with given variable names, and further that there are issues with the new constructor, which I use as a fundamental part of many code.

I'm not totally sure if this means I want a method associated with a class or an object.

Could someone advise, bearing in mind that I may not have asked this with the right technical terms — more a question out of curiosity to learn than anything. Thanks.

4
  • 1
    You're looking to extend a prototype. Commented Mar 30, 2014 at 23:36
  • Of course it is, for an example, though, we'd need to know what your new method is supposed to be doing, and which prototype you want to extend. Commented Mar 30, 2014 at 23:39
  • possible duplicate of Javascript : How to create global functions & variables Commented Mar 30, 2014 at 23:39
  • It's "mutating a sequence of DNA" i.e. changing a string at specified character index. JS has no option to do so other than substr(start)+change+substr(the rest), I was looking for a way to avoid making really ugly code in the process Commented Mar 30, 2014 at 23:41

1 Answer 1

2

This is how you can use the prototype to add functions dynamically to existing Javascript objects. This is just a random example, you'll want to use a different method than substring.

if (typeof String.prototype.editAt !== 'function') {
    String.prototype.editAt = function(index) {
        return this.substring(index);
    };
}

var myString = "hello";
var editString = myString.editAt(1);
Sign up to request clarification or add additional context in comments.

4 Comments

No substring's exactly what I want! Well, substr() Cheers!
For the virtual record, final code to do this was as above except function(index,mut) {return this.substr(0,index)+mut+this.substr(index+1,this.length); } :)
@Immx—It should also be noted that extending built–in objects is not recommended because it breaks for..in enumeration of object properties, may interferre with future extensions to ECMAScript and may interferre with extensions by others coding in the same space. However, these may not be issues you care about.
@RobG Breaking encapsulation is the term for that I think and a reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.