简体   繁体   中英

JavaScript Object and Primitive

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.

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"));

I recommend to always "use strict" mode so that you get exceptions when you try to use undeclared variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM