要使一个子类继承父类,需要两步实现:
第一:继承父类自身的属性和方法
第二:继承父类原型上的方法
-
"父类自身"属性和方法的继承
function Person(name, age){ this.name = name; this.age = age; this.sayHello = function() { console.log('hello'); }; } Person.prototype.sayName = function(){ console.log(this.name); } Person.prototype.sayAge = function(){ console.log(this.age); } function Student(name, age, sex) { // 如果要继承其他类的属性和方法,就是需要改变this的指向——将this指向使用Student创建的实例对象;为什么是改变this的指向呢?考虑使用new创建一个对象实例需要执行的四个步骤,就可以理解为什么需要改变this了 //方法一:使用call改变this,传入参数列表(call与apply不同的是call传入的是参数列表,而apply传入的是数组或类数组对象) Peron.call(this, name, age); //方法二:使用apply改变this Person.apply(this, arguments); //方法三:使用bind改变this,返回一个新函数,并且将this指向传入的第一个参数(注意:是返回一个新函数,bind后面的this指向的是使用Student创建的实例对象) Person.bind(this)(name, age); this.sex = sex; } var hexon = new Student('hexon', 17, 'male'); console.log(hexon.name); console.log(hexon.age); console.log(hexon.sex); hexon.sayHello(); // 以下两句报错,提示hexon上没有这两个方法 hexon.sayName(); hexon.sayAge();
注意:以上只能继承"父类自身"的属性和方法,并不能继承Person原型上的方法
-
继承"父类"原型上的方法
要继承父类原型上的方法,就是要将子类的prototype指向父类的prototype两种方法:
第一种:
Object.create()
方法
Object.create()
方法:创建一个拥有指定原型和若干属性的对象,并将其返回function Person(name, age){ this.name = name; this.age = age; this.sayHello = function() { console.log('hello'); }; } Person.prototype.sayName = function(){ console.log(this.name); } Person.prototype.sayAge = function(){ console.log(this.age); } function Student(name, age, sex) { // 如果要继承其他类的属性和方法,就是需要改变this的指向——将this指向使用Student创建的实例对象;为什么是改变this的指向呢?考虑使用new创建一个对象实例需要执行的四个步骤,就可以理解为什么需要改变this了 //方法一:使用call改变this,传入参数列表(call与apply不同的是call传入的是参数列表,而apply传入的是数组或类数组对象) Peron.call(this, name, age); //方法二:使用apply改变this Person.apply(this, arguments); //方法三:使用bind改变this,返回一个新函数,并且将this指向传入的第一个参数(注意:是返回一个新函数,bind后面的this指向的是使用Student创建的实例对象) Person.bind(this)(name, age); this.sex = sex; } // 将Student的原型指向Prson的原型对象 Student.prototype = Object.create(Person.prototype); // 因为prototype原型对象中有一个constructor,它指向对象的构造函数, // Peroson.prototype.constructor ==> Person,因此Student.prototype.constructor ==> Person, // 所以需要手动将Student.prototype.constructor ==> Student Student.prototype.constructor = Student; //以上两句便完成了原型的继承 Student.prototype.saySex = function(){ console.log(this.sex); } var hexon = new Student('hexon', 17, 'male'); console.log(hexon.name); console.log(hexon.age); console.log(hexon.sex); hexon.sayHello(); // 以下两句就不会报错 hexon.sayName(); // 输出 hexon hexon.sayAge(); // 输出 17
第二种方法:
function fn(){} // 创建一个空函数 fn.prototype = Person.prototype; // 将该函数的prototype指向Person.prototype Student.prototype = new fn(); // new 一个fn()对象实例,该对象实例的原型对象指向Person.prototype,这样Student.prototype就指向了Person.prototype Student.prototype.constructor = Student;
网友评论