继承提供了2个有用的任务:
1.代码重用
2.引入了一套类型系统的规范,因为程序员无需编写显示类型转换的代码,他们的工作量将大大减轻。这是一件很好的事情,应为类型转换会丧失类型系统在安全上的优势。
在基于类的语言中,对象是类的实例,并且类可以从另一个类继承,javascript是一门基于原型的语言,这意味着对象直接可以从其他对象继承。
伪类:
JavaScript is conflicted about its prototypal nature. Its prototype mechanism is
obscured by some complicated syntactic business that looks vaguely classical.
Instead of having objects inherit directly from other objects, an unnecessary level of
indirection is inserted such that objects are produced by constructor functions.
When a function object is created, the Function constructor that produces the function
object runs some code like this:
它不直接让对象从其他对象继承,反而插入了一个多余 的间接层:通过构造器函数产生对象。当一个函数
对象被创建时,Function构造器产生的函数对象会运行类似这样的一些代码:
this.prototype = {constructor: this};
The new function object is given a prototype property whose value is an object containing
a constructor property whose value is the new function object. The
prototype object is the place where inherited traits are to be deposited. Every function
gets a prototype object because the language does not provide a way of determining
which functions are intended to be used as constructors. The constructor
property is not useful. It is the prototype object that is important.
When a function is invoked with the constructor invocation pattern using the new
prefix, this modifies the way in which the function is executed. If the new operator
were a method instead of an operator, it could have been implemented like this:
(注:method方法如下:
Function.prototype.method=function(name,func){
if(!this.prototype[name])
this.prototype[name]=func;
return this;
};
通过给Functon.protoype增加一个method方法,我们下次给对象增加方法时就不用键入prototype这几个字符,省掉了一点麻烦)