【问题标题】:I am not able to understand when to use __proto__ and prototype [duplicate]我无法理解何时使用 __proto__ 和原型 [重复]
【发布时间】:2021-05-05 16:53:55
【问题描述】:
 let person ={
        name:"ayush",
        class:12
    }
function man(){
        
    }

如果我写 man.proto 函数 man,它会给出 ƒ () { [native code] }

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

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

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

为什么对象和函数的结果不同?

【问题讨论】:

  • 简单,千万不要使用__proto__
  • 您可能对基本原理感到困惑。基本规则是对象new f() 的原型是f.prototype 这对您有意义吗?如果是,那么您可以找出自己问题的答案;绘制一个图表,其中框是对象,标记的箭头是对象的属性将有所帮助。如果不是,请努力了解基础知识。
  • 一旦您在脑海中掌握了基本规则,那么您的观察就开始有意义了。为什么person.prototype 未定义?因为没有new person() 这样的东西。如果person 是一个函数,那么它需要一个.prototype 属性,以便new person() 的原型是person.prototype。但person 不是函数。这对你有意义吗?如果没有,你能问一个更集中的问题来解除你的阻碍吗?
  • 要理解发生了什么,您需要知道的另一件事是:person 的行为就像是 new Object(),所以它的原型是 Object.prototypeman 的行为就像是 new Function(),所以它的原型是 Function.prototype。这一切都遵循基本规则。
  • 您能告诉我任何可以学习原型基础知识的资源吗?因为我是编程新手,今天在完成 java 脚本的基础知识后才开始原型概念

标签: javascript oop prototype


【解决方案1】:

您永远不应使用 .__proto__ 属性 it still exists for backwards compatibility,但它被认为已弃用,取而代之的是 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

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多