[英]How to show all properties and methods of an object in javascript?
[英]How to get all the methods of an object ? [Javascript]
const str = new String('john');
console.log(str instanceof String); // true
console.log(Object.getOwnPropertyNames(str)) // [ '0', '1', '2', '3', 'length' ]
console.log(Object.getOwnPropertyNames(String)) // [ 'length', 'name', 'prototype', 'fromCharCode', 'fromCodePoint', 'raw' ]
盡管str是String的實例,但是為什么它沒有String的屬性? 以及為什么在Object.getOwnPropertyNames(str)
未顯示toLowerCase
, toString
等
您需要使用Reflect.getPrototypeOf
獲取原型對象,並列出所有自己的屬性。
const str = new String('john'); console.log(str instanceof String); console.log(Object.getOwnPropertyNames(str)); console.log(Object.getOwnPropertyNames(Reflect.getPrototypeOf(str)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
這是因為對象的原型在對象的實例上不可用,但是還有另一個__proto__
。
PS。 一篇描述此概念的好文章https://hackernoon.com/understand-nodejs-javascript-object-inheritance-proto-prototype-class-9bd951700b29
實例化對象(本機或自定義)時,將自動繼承其所有方法。 同樣,所有本機對象的方法都在__proto__
:因為最好將這些方法放在原型中以節省內存空間。
根據我在Javascript方面的個人經驗,繼承方法並不意味着它屬於您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.