0
var s = "Hi";

Date.now = function (){
    return new Date();
}

s.createdOn = function (){
    return new Date();
}

alert(s.createdOn()); // This is not working
alert(Date.now()); // This works fine

Am i violating any rule. Because i can add new property to Date class but not to string class. why?

3
  • Is there any specific reason why you would want to extend specifically string in this way? A custom object might be a better fit and more logical. Commented Apr 14, 2012 at 7:24
  • I am just curious to know why it s not working. No any specific reason Commented Apr 14, 2012 at 7:34
  • Ok, then @UNNI has provided a very good explanation :) Commented Apr 14, 2012 at 7:36

2 Answers 2

4

The reason you can't add properties or methods to a string literal is that when you try to access a literal's property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object's properties or methods. This means a String literal can only access a string's default properties or methods and those that have been added as prototypes.

More info can be obtained from this link:

http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_Reference

Hope this will help you


Sign up to request clarification or add additional context in comments.

Comments

1

replace:

var s = "Hi";

with

var s = {};

3 Comments

May i know how t make diffence?
it's explained with @UNNI's answer. and why are you appending methods to a string anyway?
am just curious to know why it s not working. No any specific reason

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.