javascript - 如何理解CoffeeScript的 `extends`关键字生成的JavaScript代码

标签 javascript coffeescript prototypal-inheritance

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

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 (我自己的博文)

关于javascript - 如何理解CoffeeScript的 `extends`关键字生成的JavaScript代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867382/

相关文章:

javascript - 如何确定 div 是否滚动到底部?

javascript - 如何使用 jQuery 制作可交换的 div 'ui cards'?

javascript - Coffeescript变量串联导致 "Uncaught TypeError value is not a function"

javascript - Object.create 中的对象属性值是常量吗?

javascript - 为什么我们在 JS 面向对象编程中使用 Prototype

javascript - 如果转换中断,则完成 CSS 更改

javascript - 试图按值而不是引用复制对象数组

javascript - 你如何在 Jakefile 中编译 CoffeeScript?

javascript - indexedDB setVersion 请求被阻止?

javascript - 为什么此 BST 验证函数在此 javascript 树实现中失败?