JavaScript Object and Primitive

3184 views javascript
5

Please I want someone to explain the code below for me:

 var f = new Number(44);

 f.name = "Yusuf";
 f.hello = function() {
   console.log("Hello");
 };

 console.log(typeof f);

 f.hello();

 console.log(f.name);
 console.log(f.toString() + "good");
 console.log(Object.prototype.hasOwnProperty(name));
 console.log(f.hasOwnProperty(hello));
 console.log(f.length);

When I check the variable type. Object gets return and I am sure this is because of the Number object constructor call function. I added two properties, one a member and a method and when I call them , it work but when I used hasOwnProperty(), false is return for the member key and undefined for the method key.

Why is it so?

where are the methods going to if the hasOwnProperty doesn't work as usual when it is supposed to when I am actually checking the property on the containing object.?

I checked Number and object object and they all return false.

answered question

you have to pass strings, not references. name -> "name", hello -> "hello" ...

Get familiar with how javascript works, because it seems you are not, look at the signature of Object.prototype.hasOwnProperty here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

1 Answer

11

The hasOwnProperty method takes the property key as a string:

console.log(Number.prototype.hasOwnProperty("name"));
console.log(Object.prototype.hasOwnProperty.call(f, "name"));
console.log(f.hasOwnProperty("name"));
console.log(f.hasOwnProperty("hello"));

posted this

Have an answer?

JD

Please login first before posting an answer.