why prototype is undefined

后端 未结 2 625
一个人的身影
一个人的身影 2021-02-02 17:04

I known this has been asked hundreds of times, however, I can\'t seem to grasp the concept of prototype

Here\'s my sample script

var config          


        
2条回答
  •  醉酒成梦
    2021-02-02 17:32

    The prototype property only exists on functions, and person is not a function. It's an object.

    Here's what's happening:

    var man = Object.create(null);         // man (object) -> null
    man.sex = "male";
    
    var person = Object.create(man);       // person (object) -> man (object) -> null
    person.greet = function () { ... };
    
    var p = Object.getPrototypeOf(person); // man (object) -> null
    alert(p.sex);                          // p is the same object as man
    
    person.prototype.age = 13;             // person doesn't have a prototype
    
    var child = function () {};            // child (function) -> Function.prototype
                                           // -> Object.prototype -> null
    child.prototype.color = "red";         // child has a prototype
    
    var ch = Object.getPrototypeOf(child); // Function.prototype
    
    alert(ch.color);                       // ch is not the same as color.prototype
                                           // ch is Function.prototype
    

    For more information I suggest you read this answer: https://stackoverflow.com/a/8096017/783743

    Edit: To explain what's happening in as few words as possible:

    1. Everything in JavaScript is an object except primitive values (booleans, numbers and strings), and null and undefined.

    2. All objects have a property called [[proto]] which is not accessible to the programmer. However most engines make this property accessible as __proto__.

    3. When you create an object like var o = { a: false, b: "something", ... } then o.__proto__ is Object.prototype.

    4. When you create an object like var o = Object.create(something) then o.__proto__ is something.

    5. When you create an object like var o = new f(a, b, ...) then o.__proto__ is f.prototype.

    6. When JavaScript can't find a property on o it searches for the property on o.__proto__ and then o.__proto__.__proto__ etc until it either finds the property or the proto chain ends in null (in which case the property is undefined).

    7. Finally, Object.getPrototypeOf(o) returns o.__proto__ and not o.prototype - __proto__ exists on all objects including functions but prototype only exists on functions.

提交回复
热议问题