0

In the book Pro Javascript design patterns one of the ways for implementing inheritance is by using an extend function.

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

Sample usage

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);

So, why can't the same function be implemented this way?

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

What is the difference between the two implementations if they are not the same?

1

1 Answer 1

1

__proto__ is not a standard JavaScript feature and it is not guaranteed to work. Most modern browsers will allow you to use it, but it's technically supposed to be an internal mechanism and you should not use it.

So that's most likely why the example didn't do it that way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.