面向对象之类与实例、类与继承
一、类与实例:
1、类的声明:
/*类的声明*/ function Animal1(){ this.name = 'name'; } /*ES6中 calss 的声明*/ class Animal2{ constructor(){ this.name = name; } }
2、生成实例:
console.log(new Animal1(),new Animal2()); /* *打印结果为 * * Animal1{name: 'name'} * Animal2{name: ''} * */
二、类与继承:
实现继承的几种方式:
1、借助构造函数实现继承(原理是在子类中改变父级this的指向,缺点是只能部分继承,
不能继承父类原型上的方法);
function Parent() { this.name = "parent"; this.list = [1, 2] } Parent.prototype.say = "Hi"; function Son() { Parent.call(this); this.type = "12"; } console.log(new Parent(),new Son()); console.log(new Son().say); //报错
2、借助原型链实现继承(缺点是原型链上的对象是共用的,改变某个对象的属性,
原型链上的其他对象属性也会改变);
function Parent(){ this.name = "parent"; this.play = [1, 23] } function Son() { this.age = 23; } Son.prototype = new Parent(); var s1 = new Son(); var s2 = new Son(); s1.play.push(4); console.log(new Person1, new Person3) console.log(s1.play, s2.play); //结果相等,都为[1,23,4]
3、组合方式(缺点是父级的构造函数执行了俩次并把父类的constructor也继承了);
function Parent() { this.name = "parent"; this.play = [1, 2]; } Parent.prototype.say = "hi"; function Son() { Parent.call(this); this.age = 12; } Son.prototype = new Parent(); console.log(new Parent(), new Son()); var s3 = new Son(); var s4 = new Son(); s3.play.push(4); console.log(s3.play, s4.play, s3.say); // [1,2,4],[1,2],hi
4、组合优化1(缺点是把父类的constructor也继承了);
function Parent1() { this.name = "parent"; } function Son1() { Parent1.call(this); this.age = 12; } Son1.prototype = Parent1.prototype; console.log(new Son1(), new Parent1()); console.log(new Son1().constructor); // function Parent1(){this.name = "parent"}
5、组合优化2(原理是通过 Object.create() 方法创建一个中间对象,参数是该对象的
原型对象,然后把子类的构造函数赋值为子类);
function Parent2() { this.name = "parent"; this.play = [1, 2]; } function Son2() { Parent2.call(this); this.age = 12; } Son2.prototype = Object.create(Parent2.prototype); Son2.prototype.constructor = Son2; console.log(new Son2); console.log(new Son2().constructor);
推荐这个方法。