function Parent() {
            this.a = 1;
            this.b = [1.2.this.a];
            this.c = { demo: 5 };
            this.show = function () {
                console.log(this.a , this.b , this.c.demo ); }}function Child() {
            this.a = 2;
            this.change = function () {
                this.b.push(this.a);
                this.a = this.b.length;
                this.c.demo = this.a++;
            }
        }
        Child.prototype = new Parent();
        var parent = new Parent();
        var child1 = new Child();
        var child2 = new Child();
        child1.a = 11;
        child2.a = 12;
        parent.show();
        child1.show();
        child2.show();
        child1.change();
        child2.change();
        parent.show();
        child1.show();
        child2.show();

Copy the code

This is a very good interview question.

  1. This point
  2. Prototype and prototype chain
  3. inheritance
  4. reference

To solve this problem, understand the following sentences:

  • For each constructor, there is a prototype [[prototype]] property pointing to the constructor’s prototype object

  • Each instance generates a new chunk of heap memory in memory

  • Each instance has an implicit prototype __proto__ pointing to the constructor’s prototype object

  • The reference to this depends on where this is called. In this case, this refers to the object where the method is called

  • Arrays and literal objects are references

  • Search rule of prototype chain: proximity principle

  • When an attribute exists on the instance, use the

  • If the instance doesn’t exist, go up the prototype chain. If it does, use the prototype chain

  • If none of the prototype chains exist, use Object on the prototype Object

  • Undefined if the prototype Object does not exist