1

Requirement : To be able to track string variables in javascript by assigning a unique ID to each variable.

Example:

var a = 'alkd';
var b = 'iquwq';  
console.log(a.id); # 1234
console.log(b.id); # 5678

What I have tried : I have tried extending string object by adding a new method or property to 'String.prototype'

Output :

console.log(a.id); #1234
console.log(b.id); #1234 (returning same id as above)

What i have observed : Ever instance of a string is inherited from String.prototype. Changes to String.Prototype object are propagated to all String instances.

Example :

a.id = 8783; # setter
console.log(b.id)# returns 8783

My Questions :

  1. Is it actually possible to get required functionality by extending String Object?
  2. Is there an alternative way to do this?
  3. Are there any plans to add this functionality to future editions of ECMAScript?
3
  • 2
    strings are immutable so there is no point in tracking it Commented Apr 1, 2015 at 5:00
  • Firstly, why? Secondly, that's the whole point of prototypes. Commented Apr 1, 2015 at 5:00
  • why wouldnt you just use a json object? a = {id: 1234, value: val}; Commented Apr 1, 2015 at 5:17

2 Answers 2

1

maybe I don't understand completely what you are trying to do, but if you want to assign an id to a variable and also have a value for that variable along with getters and setters, you can just use a json object

// initialize
var a = {id: 0, value: "zero"};

// get
console.log(a.id);
console.log(a.value);

// set
a.id = 1;
a.value = "one";

// get
console.log(a.id);
console.log(a.value);
Sign up to request clarification or add additional context in comments.

Comments

0

To answer your questions:

1) Nope. What you have observed is correct. Modifying a prototype affects all objects that utilize that prototype. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

2) Yes. Rather than using primitives, you can use a simple object like so:

var a = {
    id: 1234,
    value: "abc"
};
var b = {
    id: 5678,
    value: "def"
};

3) Probably not... See 1 :)

Comments

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.