Javascript acting wack!

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Javascript acting wack!

Post by JellyFish »

I don't know if it's just my browser or some error by me but when I write this into my firebug console:

Code: Select all

 
String.prototype.myFunction = function () {
alert("Hello");
}
 

Code: Select all

 
new String().myFunction(); //returns and alert message displaying "Hello"
 

Code: Select all

 
"".myFunction(); // returns an error(a "type error"). [i]TypeError: "".myFunction is not a function[/i]
 
I distinctly remember being able to extend the prototype of string primitives through the String object's prototype. But now I can't?

1wrd: WTF?
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Javascript acting wack!

Post by kaszu »

Code: Select all

var a = new String("...")
Creates new String object, so it gets all methods of its prototype, but

Code: Select all

var b = "...";
doesn't creates new object, but it is automatically converted to string object (seems firebug has some problems here).

Problem is with Firebug, if you will insert your code into html page it will work.
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Re: Javascript acting wack!

Post by JellyFish »

I see. Yeah I tried this out in safari's snippet editor and it worked.

So you say that string primitives aren't objects but are converted to objects? Why does Firebug/Web Inspector have trouble at this moment? What's going on?
Post Reply