inherits实现 发表于 2017-08-23 | 分类于 前端 | 评论数: 本文字数: 1.1k | 阅读时长 ≈ 1 分钟 inherits实现12345678910111213141516171819202122232425262728293031if (typeof Object.create === 'function') { // 1. 判断是否具备Object.create方法 // 2. 定义inherits方法 function inherits(ctor, superCtor) { ctor.super = superCtor; // 3. 设置“子类”构造函数原型对象 // Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__ // 通过Object.create()方法设置“子类”构造函数原型对象的__proto__为“父类”构造函数原型 // 另外将“子类”构造函数原型对象的constructor设回为“子类”构造函数 ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }} else { // 4. 若不支持Obeject.create()方法 function inherits(ctor, superCtor) { ctor.super = superCtor; // 5. 创建一个临时空构造函数 var tempCtor = function() {}; // 6. 使“父类”构造函数prototype对象寄生到临时空构造函数 tempCtor.prototype = superCtor.prototype; // 7. 使“子类”构造函数prototype对象为临时构造函数实例, ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }} 你的支持将鼓励我继续创作! 打赏 微信支付 支付宝 本文作者: Lyzhou 本文链接: https://zhouleyan.github.io/2017/08/23/fe-inherits/ 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!