本文约定:不特殊声明的情况下,属性代指属性或方法。
创建对象、对象继承实际上是一回事:我们所需要的实例对象通过构造函数获得私有属性、通过原型链获得共享的属性。什么是好的方式?私有属性通过构造函数的方式获得(不考虑实例中自定义私有属性)且不需要重写,共享属性通过原型链找到且不需要重复创建。
普适的方式
组合使用构造函数模式和原型模式创建对象
function HNU_student(name) { this.name = name; this.sayName = function() { return this.name; };}HNU_student.prototype = { school: 'HNU', saySchool: function() { return this.school; }};Object.defineProperty(HNU_student, 'constructor', {value: HNU_student});var hiyohoo = new HNU_student('xujian');
通过字面量的方式会重写prototype,且原型的constructor指向了Object,必要的情况下需要重新定义constructor。
寄生组合式继承
function object(o) { function F() {}; F.prototype = o; return new F();}function inheritPrototype(child, parent) { var prototype = object(parent.prototype); prototype.constructor = child; child.prototype = prototype;}function HNU_student(name) { this.name = name; this.sayName = function() { return this.name; };}HNU_student.prototype.school = 'HNU';HNU_student.prototype.saySchool = function() { return this.school;};function Student_2011(name, number) { HNU_student.call(this, name); this.number = number; this.sayNumber = function() { return this.number; }}inheritPrototype(Student_2011, HNU_student);Student_2011.prototype.graduationTime = 2015;Student_2011.prototype.sayGraduationTime = function() { return this.graduationTime;};var hiyohoo = new Student_2011('xujian', 20110803203);
object()的作用:将作为参数传入的对象变成实例的原型,该对象的属性被所有实例共享。
共享属性:inheritPrototype(Student_2011, HNU_student);,子构造函数原型成为超构造函数原型的一个实例,超构造函数原型中的属性共享给子构造函数。
私有属性:HNU_student.call(this, name);,通过子构造函数创建实例时调用超构造函数创建私有属性。
创建对象的其他方式
动态原型模式
function HNU_student(name) { this.name = name; this.sayName = function() { return this.name; }; if (!HNU_student.prototype.school) { HNU_student.prototype.school = 'HNU'; HNU_student.prototype.saySchool = function() { return this.school; }; }}var hiyohoo = new HNU_student('xujian');
将定义在原型中的共享属性放入构造函数中,使用判断语句,在第一次调用构造函数创建实例时,初始化原型共享属性。
寄生构造函数模式
function SpecialArray() { var values = new Array(); values.push.apply(values, arguments); values.toPipedString = function() { return this.join('|'); }; return values;}var colors = new SpecialArray('red', 'black', 'white');
新闻热点
疑难解答
图片精选