noob
noob

Reputation: 9202

JavaScript Object

I can easily create and object in a lot of different. For example like this:

var myObject = {
    myFunction: function () {
        return "";
    }
};

So if I alert this object I get something this:

[object Object]

Now I'm if I alert the NaN object I get this:

NaN

And I can still call function from it:

alert(NaN.hasOwnProperty().toString());

So my question is how can I create a object like the NaN object?

  1. If I alert it, it should return something like myObject
  2. I should be able to create and call functions on it like myObject.myFunction();

Upvotes: 0

Views: 222

Answers (4)

Esailija
Esailija

Reputation: 140210

    function MyObject(){}

    MyObject.prototype = {

        toString: function(){
            return "myObject";
        },

        myFunction: function(){

        }

    };

var myObject = new MyObject();

alert( myObject );
//myObject

Upvotes: 3

Umesh Patil
Umesh Patil

Reputation: 10685

alert(NaN.hasOwnProperty().toString()); // says false. 
alert(typeof NaN); //says it is a number

So, I don't think NaN is an Object and It's datatype is a number.

For more info: NaN means Not-a-Number. Even datatype is number, it is not a number. When any mathematical calculation can't return number,it returns NaN. The isNaN() function determines whether a value is an illegal number (Not-a-Number).This function returns true if the value is NaN, and false if not.

For example,

var num=35;
var num2=num/'asg';
console.log(num2); //returns NaN

Upvotes: 2

Alnitak
Alnitak

Reputation: 339786

Only objects that are created using a constructor function get their class name displayed using console.log(), as shown in @Esalijia's answer.

Even then, it'll be the class name that's displayed, not the name of whatever variable you happened to assign the object to.

Adding a toString() method to the object will however change the output of the alert() function, since that always looks for the presence of that method and use it if it exists.

So, writing:

var myObj = {
    toString: function() { return "boo"; }
}
alert(myObj)

will show boo in the alert box, instead of [Object object].

Upvotes: 2

Andy E
Andy E

Reputation: 344497

NaN is a number primitive, not an object. Like all primitives, it is converted to an object when you use the . operator to access a property or method that exists on the creator class's prototype.

To display properties available for primitives, either convert them to an object, or use console.dir()

console.dir(NaN);
console.log(Object(NaN));

All primitives behave this way, when you call console.log on any of the following, they exhibit the same behaviour:

console.log("Hello");
console.log(1);
console.log(true);

Yet, you can access properties on them like normal objects:

"Hello".length;
1 .toString();
true.valueOf();

Upvotes: 1

Related Questions