//Animal构造函数
function Animal(name) {
this.name = name;
}
//重写Animal的prototype对象
Animal.prototype = {
sex : "famale",
say : function() {
alert("animal");
}
}
function people(name) {
this.name = name;
}
people.prototype = new Animal("animal");
people.prototype.say = function() {
alert("peopel")
};
//一定要创建新的对象,不要直接:people.say()或people.sex;因为people还没有实例化
var zhangsan = new people("zhangsan");
alert(zhangsan.sex);//famale
zhangsan.say();//people
//没有重写prototype,此时默认的是继承object的prototype object
function cat() {
}
alert( function() {} instanceof Object);//true
alert( typeof Animal.prototype);//object
alert( typeof Animal.constructor);//function
alert(Animal.prototype.constructor == Animal);//false
alert(cat.prototype.constructor == cat);//true
在上例中,演示了people集成animal的属性过程,从下面的alert语句的结果中,可以验证 用
object={
prototype:{
constructor:this
}
}
描述的正确性,这只是大致内部结构的描述,有力于理解原型继承。
举一反三,那么可以继续构造其他种类对象,使用原型对象指向people,从而形成继承链。
比如people的sex属性,程序先查找people自身的sex属性,如果没有,那么就去查找prototype所指向的对象的sex,如果有,正好,如果没有,那么就继续查找该对象的prototype所指向的对象,顺着链一直找到object为止,如果还没有返回undefine
以下是Javascript:The Definitive Guide中关于Prototype的原文,以供参考:
Every JavaScript object has a second JavaScript object (or null,but this is rare) associated with it.
This second object is known as a prototype, and thefirst object inherits properties from the prototype.
All objects created by object literals have the same prototype object, and we can refer
to this prototype object in JavaScript code as Object.prototype. Objects created using
the new keyword and a constructor invocation use the value of the prototype property
of the constructor function as their prototype. So the object created by new Object()
inherits from Object.prototype just as the object created by {} does. Similarly, the
object created by new Array() uses Array.prototype as its prototype, and the object
created by new Date() uses Date.prototype as its prototype.
Object.prototype is one of the rare objects that has no prototype: it does not inherit
any properties. Other prototype objects are normal objects that do have a prototype.
All of the built-in constructors (and most user-defined constructors) have a prototype
that inherits from Object.prototype. For example, Date.prototype inherits properties
from Object.prototype, so a Date object created by new Date() inherits properties from
both Date.prototype and Object.prototype. This linked series of prototype objects is
known as a prototype chain.