注意:博文中提到的“属性”,指的是“属性+方法”,这里统称为“属性”;html
var obj = new Object(); 使用构造函数new一个对象实例(因此程序员每天都在谈对象,哈哈哈)程序员
特色:app
function Animal() { this.type = '动物'; } Animal.prototype.getType = function(){ console.log(this.type); } let animal = new Animal(); console.log(animal.type); // 动物 animal.getType(); // 动物
Child.prototype = new Parent(); 将父类的实例做为子类的原型ssh
特色:函数
function Animal() { this.type = '动物'; } Animal.prototype.getType = function(){ console.log(this.type); } function Cat(){ this.vary = '猫'; } Cat.prototype.getVary = function(){ console.log(this.vary); } Cat.prototype = new Animal(); var cat = new Cat(); // cat.getVary() // 报错:cat.getVary is not a function [缘由:Cat.prototype = new Animal()的操做覆盖了原型链] console.log(cat.constructor); // Animal 这个constructor实质调用的是Animal.prototype.constructor // 修改Cat类的constructor为Cat Cat.prototype.constructor = Cat; console.log(cat.constructor); // Cat cat.getType(); // 动物 // 修改Cat类prototype上的getType方法,看是否影响Animal类的getType方法 Cat.prototype.getType = function(){ console.log('我是猫科类'); } var animal = new Animal(); animal.getType(); // 动物
在子类的构造体中,使用call、apply、bind方法,让父类方法中的this指向子类的实例,也就是改变this的上下文环境。学习
特色:this
Function.prototype.call2 = function () { var ary = [...arguments].slice(1); if (!arguments[0]) { this(...ary); } else { var obj = Object(arguments[0]); // 将参数变成一个对象 obj.__proto__.fn = this; obj.fn(...ary); delete obj.__proto__.fn; } };
function Animal() { this.type = '动物'; } Animal.prototype.getType = function(){ console.log(this.type); } function Cat(){ Animal.call(this); this.vary = '猫'; } Cat.prototype.getVary = function(){ console.log(this.vary); } var cat = new Cat(); console.log(cat.type); // 动物 // cat.getType(); // Uncaught TypeError: cat.getType is not a function cat.type = '猫科动物'; var animal = new Animal(); console.log(animal.type); // 动物
var child = Object.create(obj, props); spa
我先来一段Object.create的实现方式(看懂原理很重要)prototype
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
咱们这里只分析参数obj的骚操做,能够看出来,Object.create是内部定义一个对象,而且让F.prototype对象赋值为引进的对象/函数 o,并return出一个对象的实例。code
只要看懂了原理,咱们能够参考“原型链继承”的方式去理解这种继承方法;
function Animal() { this.type = '动物'; } Animal.prototype.getType = function(){ console.log(this.type); } var cat = Object.create(new Animal(), { vary: { value: '猫科动物' } }); console.log(cat.constructor); // Animal 这个constructor实质调用的是Animal.prototype.constructor console.log(cat.type); // 动物 cat.getType(); // 动物 console.log(cat.vary); // '猫科动物'