如何理解由 CoffeeScript 的 'extends' 关键字生成的 JavaScript 代码

How to understand the JavaScript code generated by CoffeeScript's `extends` keyword

本文关键字:JavaScript 代码 关键字 extends 何理解 CoffeeScript      更新时间:2023-09-26

这是由CoffeeScript的extends关键字生成的JavaScript代码。原型链是如何设置的?

var __hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { 
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    function ctor() { this.constructor = child; } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype; 
    return child; 
};
var __hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) {
    // Copy "static" attributes from the parent constructor to the child constructor
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    // This is the surrogate constructor, used so you don't need
    // to instantiate an instance of the parent just to setup the prototype chain
    // the statement in the surrogate constructor properly attaches
    // the constructor property to object
    function ctor() { this.constructor = child; }
    // Attach the parent's prototype to the surrogate constructor
    ctor.prototype = parent.prototype; 
    // This is setting up the chain, attaching an instance of a constructor whose
    // prototype is set to the parent to the prototype property of the child
    // In naive implementations, this would be child.prototype = new parent();
    child.prototype = new ctor; 
    // Allows access to the parent from user code, and used by the `super` keyword
    child.__super__ = parent.prototype; 
    return child; 
};

请参阅 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html(我自己的博客文章)