簡體   English   中英

如何獲得對象的所有方法? [使用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)未顯示toLowerCasetoString

您需要使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM