-
-
Save allenfantasy/1e666aedf134938d7802 to your computer and use it in GitHub Desktop.
Implementation of inheritance in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var __hasProp = {}.hasOwnProperty; | |
| var __extends = function(child, parent) { | |
| for (var key in parent) { | |
| if (__hasProp.call(parent, key)) child[key] = parent[key]; | |
| } | |
| function ctor() { | |
| // why set the prototype's constructor to child? | |
| this.constructor = child; | |
| } | |
| ctor.prototype = parent.prototype; | |
| child.prototype = new ctor(); | |
| child.__super__ = parent.prototype; | |
| return child; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
回答自己之前提出来的问题:child 和 parent 都是构造函数,但函数本身也可能带有属性(类似于基于类的OOP语言中的
class variable),所以需要复制给子构造函数。避免子构造函数通过 prototype 污染 Parent 对象的方法的关键在于
ctor。请看例子:这段代码在最后尝试对
Student.prototype进行修改,也就是我们所理解的重定义(override)。如果在__extends函数中不使用ctor作为过渡:则会出现以下情况: