javascript - 我无法理解何时使用 __proto__ 和原型
问题描述
let person ={
name:"ayush",
class:12
}
function man(){
}
如果我写人,则在功能人的情况下。proto它给出 ƒ () { [native code] }
当我写 man.prototype 我得到 {constructor: ƒ}
但在对象人的情况下,如果我写人的话。proto它给了我 {constructor: ƒ, defineGetter : ƒ, defineSetter : ƒ, hasOwnProperty: ƒ, lookupGetter : ƒ, ...}
当我写 person.prototype 时,它给出了 undefined
为什么在对象和函数的情况下结果会有所不同?
解决方案
您永远不应该使用该.__proto__
属性,它仍然存在以实现向后兼容性,但被认为已弃用,取而代之的是Object.getPrototypeOf()
.
现在解释一下你观察到的情况:
let person = {
name: "ayush",
class: 12
}
function man() {}
console.log(Object.getPrototypeOf(person));
// Object.prototype because person is an instance of Object
console.log(person.prototype);
// undefined because an object has no prototype property, it's not a constructor function
console.log(Object.getPrototypeOf(man));
// Function.prototype
console.log(man.prototype);
// object. man.prototype is actually an empty object to be filled with
// methods for future use as a constructor function with the new operator
推荐阅读
- java - 使用socket服务器和des算法加解密
- python - 绘制宽度较小的 pygame 矩形
- html - 如何避免动画元素在放大页面时扩展页面
- python - what is the order of mathematical calculations in python?
- kubernetes - Ubuntu 20.04 qemu-kvm 共享文件夹
- amazon-athena - 我需要在 Athena AWS 中使用 INSTR
- javascript - 模糊页面上所有输入的最佳方法?
- excel - 在 excel vba 中排序时出现应用程序错误
- php - 尝试从数据库表中进行基本减法
- javascript - 在 React 中管理组件功能的正确方法