Javascript继承不同的扩展函数实现

时间:2017-06-24 18:08:18

标签: javascript inheritance prototype

在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
}

如果它们不相同,两个实现之间有什么区别?

1 个答案:

答案 0 :(得分:1)

__proto__不是标准的JavaScript功能,但无法保证其正常运行。大多数现代浏览器都允许您使用它,但它在技术上应该是一种内部机制,您不应该使用它。

这很可能是为什么这个例子没有这样做。