构造函数的方法,我们通过原型对象(prototype)实现继承,其属性我们则是通过call、apply、bind,这三个方法实现继承
首先,我们先写两个函数
function Father(uname, age) { this.uname = uname; this.age = age; } Father.prototype.money = function() { console.log('努力挣钱'); } function Son(uname, age, score) { // 使 Son 里面的 this 指向 Father Father.call(this, uname,age); this.score = score; }我们可以通过代码 Father.call(this, uname,age); 改变 This 指向,继承属性,但是我们改如何实现方法的继承呢?
我们的方法用原型对象来继承的,那么我们直接把 Father的原型对象赋值给 Son的原型对象不也就可以了,代码如下:
Son.prototype = Father.prototype;这样做之后我们的 Son 确实有了 Father 函数里面的方法,实例化输出一下 Son 可得到:
var son = new Son(); console.log(son);但是,如果我们修改了 Son 构造函数的方法之后,会不会对父构造函数造成一些影响呢? 下面给 Son 添加一个方法:
Son.prototype.exam = function () { console.log('好好考试'); }输出一下 Father的原型对象:
var father = new Father(); console.log(Father.prototype);我们可以发现,Father构造函数也被改变了。那这又是为什么呢? 由于我们上面 Son.prototype = Father.prototype; 把 Father原型对象赋给 Son原型对象,就把 F原( Father原型对象简称,下同)的地址给了 S原(Son原型对象,下同),这时我们如果修改 S原 那么由于地址指向 F原 也会跟着修改。
那么我们如何才能做到,既能给 Son 添加方法,又不会改变 Father 的方法呢? 我们也可以做这样的操作
function Father(uname, age) { this.uname = uname; this.age = age; } Father.prototype.money = function() { console.log('努力挣钱'); } function Son(uname, age, score) { // 使 Son 里面的 this 指向 Father Father.call(this, uname,age); this.score = score; } // Son.prototype = Father.prototype; 这样赋值有问题,如果修改了 S原,F原 也跟着改变 Son.prototype = new Father(); //这样赋值,如果改变子 S原,F原不会改变Son.prototype = new Father(); 这样赋值,如果改变 S原,F原 不会改变,相当于把 Father 实例化(下面简称:F实),S原 指向的是 F实,F实又通过对象原型(__ proto__)指向 F原。这样即使修改了 S原 也不会改变 S原。 由于上面我们做了这样的操作:
Son.prototype = new Father();那么这样做我们的 S原 会不会有所改变呢? 接下来我们输出看一下:
console.log(Son.prototype.constructor);Son原指向的是 Father,接下来我们班Son原指向 Son 原,做法跟构造函数属性的继承差不多,向代码中添加:
Son.prototype.constructor = Son;完整的代码如下所示:
function Father(uname, age) { this.uname = uname; this.age = age; } Father.prototype.money = function() { console.log('努力挣钱'); } function Son(uname, age, score) { // 使 Son 里面的 this 指向 Father Father.call(this, uname,age); this.score = score; } // Son.prototype = Father.prototype; 这样赋值有问题,如果修改了子原型对象,父原型对象也跟着改变 Son.prototype = new Father(); //这样赋值,如果改变子原型对象,父原型对象不会改变 // 利用对象的形式修改了原型对象,那么就要用 constructor 指回原来的构造函数 Son.prototype.constructor = Son; Son.prototype.exam = function() { console.log('孩子考试'); } var son = new Son(); console.log(son); var father = new Father(); console.log(father); console.log(Son.prototype.constructor);