三,构造函数的继承
ES6之前并没有 extends 继承,我们之前都是通过 构造函数 + 原型对象 模拟继承,被称为
组合继承
1,call方法使用
-
call()
使用
// call方法 function fn(x, y) { console.log(x + y); console.log('this的指向:', this); } var a = { name: 'xyb', age: 20 } // 1. call方法可以调用函数 fn.call(null, 1, 2); // this的指向: Window {po....} // 2. call方法可以改变this的指向 fn.call(a, 1, 2); //this的指向: {name: "xyb", age: 20}
2,继承属性
-
通过 call() 方法,在子构造函数里面调用父构造函数,并改变 this 指向
// 1. 父构造函数 function Father(name, age) { this.name = name; this.age = age; } // 2. 子构造函数 function Son(name, age) { // 把之后父构造函数中的this改变成son的this指向 Father.call(this, name, age) } var xyb = new Son('xyb', 20); console.log(xyb); // Son {name: "xyb", age: 20}
3,继承方法
-
错误的写法
// 1. 父构造函数 function Father(name, age) { this.name = name; this.age = age; } Father.prototype.say = function() { console.log('能说话'); } // 2. 子构造函数 function Son(name, age) { Father.call(this, name, age); } Son.prototype = Father.prototype; // 错误的写法,和父亲的原型对象是同一个,一个修改都会修改 var xyb = new Son('xyb', 20); Son.prototype.haha = function() {}; console.log(Father.prototype); // {say: ƒ, haha: ƒ, constructor: ƒ} 父亲的也被修改了!!
-
正确的写法
// 1. 父构造函数 function Father(name, age) { this.name = name; this.age = age; } Father.prototype.say = function() { console.log('能说话'); } // 2. 子构造函数 function Son(name, age) { Father.call(this, name, age); } Son.prototype = new Father(); // 重新new一块新的Father空间,这样就能和Father构造函数的原型隔离 Son.prototype.constructor = Son; var xyb = new Son('xyb', 20); console.log(xyb.__proto__.constructor); // 构造函数指回Son
4,类的本质
类的本质就是,构造函数的另外一种写法,是构造函数的语法糖
构造函数的特点:
-
构造函数的原型对象是 prototype
-
构造函数的原型里面有一个 constructor 构造函数,指回构造函数
-
构造函数可以通过原型 prototype 添加方法
-
构造函数的实例有
__proto__
属性,并且指向构造函数的原型对象上class Peopel { constructor(name, age) { this.name = name this.age = age; }; sing() { console.log('唱歌了'); } } var a = new Peopel('xyb', '20'); console.log(typeof Peopel); // function, 本质上是一个函数 console.log(a.__proto__); // {constructor: ƒ, sing: ƒ} 有一个构造函数和方法 console.log(Peopel.prototype); // {constructor: ƒ, sing: ƒ} console.log(a.__proto__ === Peopel.prototype); // true console.log(a.__proto__.constructor); // 类本身