JavaScript inheritance extend function

后端 未结 1 876
时光说笑
时光说笑 2020-12-13 22:09

I\'m having some trouble understanding the IF clause at the end of this function from Pro JavaScript Design Patterns:

function extend(subClass, superClass) {         


        
相关标签:
1条回答
  • 2020-12-13 22:41

    The problem that those two lines try to avoid, is generally produced when you replace the prototype property of a Constructor Function, for example:

    function Foo () {};
    Foo.prototype = {
      bar: 'baz'
    };
    
    var foo = new Foo();
    foo.constructor === Object; // true, but `constructor` should refer to Foo
    

    When functions objects are created, the prototype property is initialized with a new object, which contains a constructor property that refers to the function itself, e.g.:

    function Bar () {};
    var bar = new Bar();
    bar.constructor === Bar; // true
    

    When you replace the prototype property with another object, this object has it's own constructor property, generally inherited from other constructor, or from Object.prototype.

    var newObj = {};
    newObj.constructor === Object;
    

    Recommended articles:

    • Constructors considered mildly confusing
    • JavaScript Prototypal Inheritance
    0 讨论(0)
提交回复
热议问题