Javascript-the Good Parts Chapter 5 inheritance

Source: Internet
Author: User

Divides one thing entire to many objects;
Like perspectives, which rightly gazed upon
Show Nothing but confusion ...
-william Shakespeare, the tragedy of King Richard the Second

Inheritance is a important topic in the most programming languages.

In the classical languages (such as Java), inheritance (or extends) provides the useful services. First, it is a form of code reuse. If a new class is mostly similar to an existing class, you are only having to specify the differences. Patterns of code reuse is extremely important because they has the potential to significantly reduce the cost of Softwar E Development. The other benefit of classical inheritance are that it includes the specification of a system of types. This mostly frees the programmer from have to write explicit casting operations, which are a very good thing because when Casting,the safety Benefits of a type system is lost.

JavaScript, being a loosely typed language, never casts. The lineage of an object is irrelevant. What's matters about a object is what it can does, not what it's descended from.

JavaScript provides a much richer set of code reuse patterns. It can ape (imitate) the classical pattern, but it also supports and other patterns that is more expressive. The set of possible inheritance patterns in JavaScript is vast. In this chapter, we'll look at a few for the most straightforward patterns. Much more complicated constructions is possible,but it's usually best-to-keep it simple.

Pseudoclassical

JavaScript is conflicted on its prototypal nature. Its prototype mechanism are obscured by some complicated syntactic business that looks vaguely classical. Instead of having objects inherit directly from the other objects, a unnecessary level of indirection are inserted such that O Bjects is produced by constructor functions.

When a-function object is created, the function constructor that produces the function object runs some code like this:

 This This};

The new function object is given a prototype property whose value was an object containing a constructor property whose Val UE is the new function object. The prototype object is the "where inherited traits is" is deposited. Every function gets a prototype object because the language does not provide a by determining which functions is inte Nded to be used as constructors. The constructor property was not useful. It is the prototype object, which is important.

When a function was invoked with the constructor invocation pattern using the new prefix, this modifies the the on which th e function is executed. If The new operator were a method instead of an operator, it could has been implemented like this:

Function.method (' new ',function ( ) {//Create A new object that inherits from the//constructor ' s prototype.    varthat = Object.create ( This. prototype);//Invoke The constructor, Binding–this-to//The new object.    varother = This. Apply (that, arguments);//If Its return value is isn ' t an object,//substitute the new object.    return(typeofother = = = ' object ' && other) | |that ;});

We can define a constructor and augment its prototype:

var function (name) {    this. Name =function  () {    returnthis       function () {return this. Saying | |  ';};

Now, we can make an instance:

var New Mammal (' Herb the Mammal '); var // ' Herb the mammal '

We can make another pseudoclass this inherits from mammal by defining it constructor function and replacing its prototype With an instance of mammal:

varCat =function(name) { This. Name =name;  This. saying = ' Meow ';};//Replace Cat.prototype with a new instance of mammalCat.prototype =Newmammal ();//Augment The new prototype with//purr and Get_name methods.Cat.prototype.purr =function(n) {varI, S = ";  for(i = 0; i < n; i + = 1) {        if(s) {s+ = '-'; } s+ = ' r '; }    returns;}; Cat.prototype.get_name=function ( ) {    return  This. says () + "+ This. Name + "+ This. says ();};varMycat =NewCat (' Henrietta ');varsays = Mycat.says ();//' Meow 'varPurr = Mycat.purr (5);//' R-r-r-r-r 'varName =mycat.get_name ();//' Meow Henrietta Meow '

The pseudoclassical pattern was intended to look at sort of object-oriented, but it's looking quite alien. We can hide some of the ugliness by using the method, and defining an inherits method:

function (parent) {    thisnew  Parent ();     return  This ;});

Our inherits and method methods return this, allowing us to program in a cascade style. We can now make your Cat with one statement.

varCat =function(name) { This. Name =name;  This. saying = ' Meow ';}.    Inherits (mammal). Method (' Purr ',function(n) {varI, S = ";  for(i = 0; i < n; i + = 1) {            if(s) {s+ = '-'; } s+ = ' r '; }        returns;    }). Method (' Get_name ',function ( ) {        return  This. says () + "+ This. Name + "+ This. says (); });

By hiding the prototype jazz, it now looks a bit less alien. But are we really improved anything? We are now having constructor functions that act like classes, but at the edges, there could be surprising behavior. There is no privacy; All properties is public. There is no access to super methods.

Even worse, there is a serious hazard with the use of constructor functions. If you forget to include the new prefix when calling a constructor function and then this is not being bound to a new object. Sadly, this is bound to the global object, so instead of augmenting your new object, you'll be clobbering global VA Riables. That's really bad. There is no compile warning, and there is no runtime warning.

This was a serious design error in the language.  To mitigate this problem, there was a convention that all constructor functions be named with an initial capital, and that Nothing else was spelled with a initial capital. This gives us a prayer that visual inspection can find a missing new. A Much better alternative is to the use of new at all.

The pseudoclassical form can provide comfort to programmers who is unfamiliar with JavaScript, but it also hides the true Nature of the language. The classically inspired notation can induce programmers to compose hierarchies that is unnecessarily deep and complicate D. Much of the complexity of class hierarchies is motivated by the constraints of static type checking. JavaScript is completely free of those constraints. In classical languages, class inheritance are the only form of code reuse. JavaScript has more and better options.

Javascript-the Good Parts Chapter 5 inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.