Prototype property throwing undefined

This question already has an answer here:

  • How does JavaScript .prototype work? 21 answers

  • The problem of confusion is that the word prototype kind of has two meanings.

    1. Function property . Any function can have a prototype property, which is an object. In your case

    Test.prototype = {
        sayHello: function() {}
    }
    

    Properties of this object become inherited properties and methods of the objects constructed with this constructor function:

    var z = new Test();
    

    Now z has a method property sayHello , which you configured with the help of the Test.prototype object.

    2. Instance prototype . The instance object, in your case z , has internal reference to the prototype object from point #1 above. This reference is used internally to resolve properties and methods in the prototype chain. However this reference is not supposed to be accessible directly, and you can't access this reference with prototype property of the instance.

    In chrome and Firefox you can use __proto__ property, but its usage is deprecated.

    To get a prototype which was used during object construction you should use Object.getPrototypeOf :

    Object.getPrototypeOf(z) === Test.prototype; // true
    

    In order to get prototype, use Object.getPrototypeOf() . So, in your example, try with Object.getPrototypeOf(z)


    you should be using getPrototypeOf method on the object.like this:

    Object.getPrototypeOf(z);
    

    you can do like this:

    Test.prototype=Object.getPrototypeOf(z);
        console.log(Test.prototype);
        console.log(Object.getPrototypeOf(z));
    
    链接地址: http://www.djcxy.com/p/30074.html

    上一篇: Javascript中使用的原型是什么?

    下一篇: 原型属性抛出undefined