2

Is Object the base class of all objects in Javascript, just like other language such as Java & C#?

I tried below code in Firefox with Firebug installed.

var t = new Object();
var s1 = new String('str');
var s2 = 'str';
console.log(typeof t);
console.log(typeof s1);
console.log(typeof s2);

The console output is

object
object
string

So, s1 and s2 are of diffeent type?

1
  • Yes, everything in JavaScript that is not a primitive data type is an Object. String is an Object that creates as a return value a primitive of the type String (from an optional input string); it is not itself a String. Check out the following link for more information: articles.sitepoint.com/article/oriented-programming-1 Commented May 11, 2010 at 18:54

3 Answers 3

7

Yes, 'str' is a string literal, not a string object.

A string literal has access to all of a string's objects and methods because javascript will temporarily cast a string literal as a string object in order to run the desired method.

Finally:

Where the two differ is their treatment of new properties and methods. Like all Javascript Objects you can assign properties and methods to any String object. You can not add properties or methods to a string literal. They are ignored by the interpreter.

Read up more here.

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

Comments

2

The process is called boxing/unboxing.

This means that whenever the interpreter/compiler sees a primitive type used as an Object then it will use

new Object([primitive])

to get a valid instance. And in the same way, as soon as you try to use it as a primitive (as in an expression) it will use

[boxedobject].valueOf()

to get the primitive.

In ECMAScript (javascript) the constructor of Object is able to box all primitives.

1 Comment

I see that the question has been edited after this answer was given, so the form of the question is now totally different...
1

Read this: http://skypoetsworld.blogspot.com/2007/11/javascript-string-primitive-or-object.html

and this: https://developer.mozilla.org/en/JavaScript/Glossary#primitive

and this: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String

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.