A对象经过继承B对象,就能直接拥有B对象的全部属性和方法。javascript
核心:子类型的原型为父类型的一个实例对象html
// 建立一个父类(注意其本质仍然是一个构造函数) function Parent() { this.name='kevin'; } // 建立父类上的一个共享方法 Parent.prototype.getName = function(){ console.log(this.name); } // 建立子类 function Child() { } // 核心代码:将父类的实例做为子类的原型 Child.prototype = new Parent(); var child1 = new Child(); console.log( child1.getName() ); // kevin
核心:借助已有的对象来建立对象,var B = Object.create(A);
,以A对象为原型,建立B对象。B继承了A对象的全部属性和方法。java
// 建立父类 function Person(name,age) { this.name = name; this.age = age; } // 建立父类共享的方法 Person.prototype.setAge = function(){ console.log(111); } // 建立子类 function Student(name, age, price) { Person.call(this, name, age); this.price = price; this.setScore = function() { } } Student.prototype = Object.create(Person.prototype); // 核心代码 Student.prototype.constructor = Student; // 核心代码 var s1 = new Student('tom', 20, 15000); console.log(s1 instanceof Student); // true console.log(s1 instanceof Person); // true console.log(s1.constructor); // Student console.log(s1); // Student {name: "tom", age: 20, price: 15000, setScore: ƒ}
总结该专题知识点的时候,找到了不少好的资源,讲的基本都是六-八种的继承方式。这里没有一一列出的缘由是但愿若是赶时间参加面试的你,能够先从这两种根本的方法去下手,有一个初步的了解,不至于问到的时候一点都不知道。git
方式一是一种最基础,最接近于常识的理解,有助于快速进入状态。方式二则是比较了几种实现的继承的方式后,一种相对来讲比较完美的作法,能够做为一个“终极”继承版原本用。有兴趣的读者,能够看看文末的连接,获取更多的继承方式的讲解。github
参考连接:
https://github.com/mqyqingfeng/Blog
http://www.javashuo.com/article/p-mbawwkga-r.html
http://www.javashuo.com/article/p-eebumefy-r.html
http://www.javashuo.com/article/p-zyrmfoxg-dk.html
http://www.javashuo.com/article/p-rwkatbxg-gb.html
https://github.com/mqyqingfeng/Blog/issues/16
http://www.ayqy.net/blog/%E9%87%8D%E6%96%B0%E7%90%86%E8%A7%A3js%E7%9A%846%E7%A7%8D%E7%BB%A7%E6%89%BF%E6%96%B9%E5%BC%8F/
https://zhuanlan.zhihu.com/p/37735247