一、了解继承
1.1 继承就是后辈继承前辈的属性和方法
1.2 面向对象编程(OOP)
? JavaScript不是面向对象编程语言, 但是它的特性支持面向对象的编程思维。
二、继承的方法
1 从父类继承属性和方法
对象冒充, 模仿java中的继承对象冒充, 模仿java中的继承。通过改变父类的执行环境进行继承;
???// 从父类中继承属性和方法 ???function Father() { ???????this.say = ‘hi‘; ???????this.fn = function () { ???????????return this.say; ???????} ???????console.log(1); //1 ???} ???????function Son() { ???????this.name = "a"; ???????//对象冒充 ???????this.f = Father; //将函数Father作为子类的方法,复制的是一个函数对象的指针 ???????this.f(); //运行函数,得到一个属性和一个方法fn,同时会执行函数 ???????????delete this.f; //删除这个指针链接 ???} ???????var s = new Son(); ???????console.log(s); ???console.log(s.fn()); //hi son存在存在了Father的方法fn
2 通过原型链继承
?原型链的查找顺序: 先自身查找, 找到就结束, 没有找到就沿着原型链向上查找, 直到找到Object.prototype.__proto__
???function A() { ???????this.a = "A"; ???????this.fn = function () { ???????????return this.a; ???????} ???} ???????function B() { ???????this.a = "B"; ???} ???????B.prototype = new A(); //将A的实例作为B的原型,原来存在于A实例的所有方法和属性,存在于B原型prototype中 ???var b = new B(); ???console.dir(b);
3 更改this指向
apply()
call()
bind()
这里就不详细概述了
4 class继承extends
???class C { ???????constructor(name) { ???????????//构造函数 ???????????this.name = name; //给新的对象添加一个name属性 ???????} ???????????// sayName相当于 A.prototype.sayName = function(){return this.name} ???????sayName() { ???????????return this.name; ???????} ???????} ???????class D extends C { //D类,该类通过extends关键字,继承了C类的所有属性和方法 ???????} ???????var newc = new D("haode"); ???console.log(newc.name); //"haode" ???console.log(newc.sayName()); //"haode"
js面向对象3-继承
原文地址:https://www.cnblogs.com/hjson/p/10228347.html