// 学习要想拷贝那么快就好了 // // JavaScript 的继承是基于 prototype 的,每个对象的 prototype 是保存在对象的 __proto__ 属性中的,这个属性是内部(internal)的属性( 惯例是内部的或者隐藏的属性以 _ 开头) // A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. // /** * Property lookup in Javascript looks within an object's own properties and, * if the property name is not found, it looks within the special object property __proto__. * This continues recursively; the process is called "lookup in the prototype chain". * The special property __proto__ is set when an object is constructed; * it is set to the value of the constructor's prototype property. * So the expression new Foo() creates an object with __proto__ == Foo.prototype. * Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo(). */ // 给对象的原型增加成员会立即在该对象中可见 function Base(){ this.name = 'myhere'; } function Sub(){ this.age = 23; } Sub.prototype = new Base(); // 给原型赋值为一个==对象==。 var me = new Sub(); // 创建对象后给原型增加 sex 属性,该属性立即在对象中可见 Base.prototype.sex = 'male'; var str = ''; str += me.name + me.age + me.sex; document.write( str); // myhere23male /** * 说明: * 对于这种继承,在频繁修改原型的情况下就变得混乱了 */ // /** * 另一种继承方法 */ function Base(){ this.name = 'myhere'; } // 并没有将 Sub 的原型赋值为 Base,只是在 Sub 中调用 Base 函数 function Sub(){ this.age = 23; Base.call( this); // 只是将一部分初始化交给 Base 函数,并没有操作 prototype } var me = new Sub(); Base.prototype.sex = 'male'; // 修改 Base 不会影响 Sub 的对象,因为 Base 并不是 Sub 的原型 // 如果将这个增加 sex 的语句放到 Sub 定义前,在 me 中也得不到 sex 属性, // 因为 Base.call() 只是调用 Base 函数而已 var str = ''; str += me.name + me.age + me.sex; document.write( str); // myhere23undefined 参考自:MDC