【问题标题】:Javascript inheritance different extend functions implementationJavascript继承不同的扩展函数实现
【发布时间】:2017-06-24 18:08:18
【问题描述】:

在 Pro Javascript 设计模式一书中,实现继承的方法之一是使用扩展函数。

function extend(subClass, superClass) {
   var F = function() {};
   F.prototype = superClass.prototype;
   subClass.prototype = new F();
   subClass.prototype.constructor = subClass;
}

示例用法

function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name;
}
function Author(name, books) {
    Person.call(this, name);
    this.books = books;
}
extend(Author, Person);

那么,为什么不能这样实现相同的功能呢?

function extend(subClass, superClass) {
    subClass.prototype.__proto__ = superClass.prototype
}

如果不一样,两种实现有什么区别?

【问题讨论】:

  • __proto__ 不被 IE developer.mozilla.org/en/docs/Web/JavaScript/Reference/… 支持

标签: javascript inheritance prototype


【解决方案1】:

__proto__ 不是标准的 JavaScript 功能,不保证可以正常工作。大多数现代浏览器都允许您使用它,但从技术上讲,它应该是一种内部机制,您不应该使用它。

所以这很可能是示例没有这样做的原因。

【讨论】:

    猜你喜欢
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 2015-02-23
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多