简体   繁体   中英

Why doesn't Object.getOwnPropertyNames() list all properties and methods?

I am trying to extract all the properties and methods from an object which happens to be a string: var str = "Hello World!"

If I use the command Object.getOwnPropertyNames(str) I get a list of properties and methods: ["0", "1", "2", "3", "length"] . However I know there are other methods like .toUpperCase() which belong to the string object but they are not listed.

My question : why is the method .toUpperCase() not listed? What can I do to list it out with many others ( .indexOf() ...)?

Here is the code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Display properties and methods from objects</title>
</head>
<body>
    <script type="text/javascript">
    var str= 'Hello World!'
    var listPropertiesMethods = Object.getOwnPropertyNames(str)
    console.log(listPropertiesMethods);
    </script>
</body>
</html>

Cause the properties you list ( indexOf , ...) are not part of the string object itself, but are rather part of its prototype:

Object.getOwnPropertyNames(
 Object.getPrototypeOf("str")
)

You have just look at the proto-type of your object and you get what you want:

console.log(str.__proto__);

在此处输入图片说明

The Object.getOwnPropertyNames(obj) method returns only the properties of the obj (like length). You can use Object.getPrototypeOf(obj) to get a more complete list of methods/properties.

Ex.:

Object.getOwnPropertyNames("Test")

(5) ["0", "1", "2", "3", "length"]

Object.getPrototypeOf("Test")

String {"", formatUnicorn: ƒ, truncate: ƒ, splitOnLast: ƒ, contains: ƒ, length: 0, …}

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