首页 > 解决方案 > 我无法理解何时使用 __proto__ 和原型

问题描述

 let person ={
        name:"ayush",
        class:12
    }
function man(){
        
    }

如果我写人,则在功能人的情况下。proto它给出 ƒ () { [native code] }

当我写 man.prototype 我得到 {constructor: ƒ}

但在对象人的情况下,如果我写人的话。proto它给了我 {constructor: ƒ, defineGetter : ƒ, defineSetter : ƒ, hasOwnProperty: ƒ, lookupGetter : ƒ, ...}

当我写 person.prototype 时,它​​给出了 undefined

为什么在对象和函数的情况下结果会有所不同?

标签: javascriptoopprototype

解决方案


您永远不应该使用该.__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


推荐阅读